Java上传图片

2021-05-08 22:28

阅读:300

标签:har   附件   指定   res   ror   default   content   文件写入   jmm   

直接上代码了。从一个功能摘取出来的,只保留了上传图片、附件的功能

1,上传图片按钮,样式需要调整。

   name="upfile" id="insertbid" enctype="multipart/form-data">
  
     
     
      

支持格式: jpg,png,JPG,PNG

  
  提交

2,js代码,使用Vue

function insert(){

var form = new FormData($("#insertbid")[0]);//获取表单

$.ajax({
url:"",
type:"POST",
dataType:"text",
data:form,
mimeType:"multipart/form-data",
contentType: false,
processData: false,
success:function(data){

if(data === "SUCCESS"){
alert("上传成功")
}else{
alert("上传失败")
}
},
})
}
$(‘#cgqd‘).change(function(){
if($("#cgqd")[0].files.length > 0) {
app.imgishows = false;
app.filenames = $("#cgqd")[0].files[0].name
}

});

/*
上传文件格式限制*/ function fileChange(target,id) { var filetypes =[".jpg",".png",".JPG",".PNG"]; var filepath = target.value; if(filepath){ var isnext = false; var fileend = filepath.substring(filepath.lastIndexOf(‘.‘)); if(filetypes && filetypes.length>0){ for(var i =0; i){ if(filetypes[i]==fileend){ isnext = true; break; } } } if(!isnext){ alert("不接受此文件类型!"); target.value =""; return false; } }else{ return false; } }

3,controller

    @RequestMapping("/insert")
    @ResponseBody
    public String projectInsert(HttpServletRequest request, MultipartFile file){
        String result = "";

        Project project = new Project();

        String fileNo = UUID.randomUUID().toString().replaceAll("-", "");//图片编号
        project.setImage(fileNo);
        FileInputUtil.addFile(purchaseSimpleNoticeService,file,fileNo);//上传图片,参数1:上传图片service接口,参数2:接收的图片,参数3:图片编号
        Integer num = iProjectService.projectInsert(project);
        if(num>0){
            result = "SUCCESS";
        }else{
            result = "ERROR";
        }
        return result;
    }

4,图片上传工具类

package cn.ljs.util;

import cn.ljs.entity.NoticeFile;
import cn.ljs.service.PurchaseSimpleNoticeService;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 图片上传工具类
 * 
 * @author Thinkpad
 *
 */
public class FileInputUtil {

    /**
     * 图片上传
     * @param purchaseSimpleNoticeService
     * @param file
     */
    public static void addFile(PurchaseSimpleNoticeService purchaseSimpleNoticeService, MultipartFile file,
            String fileNo) {
        // 保存附件,未指定盘时一般为电脑的最后一个盘
        String realUploadPath = "/image/file";
        // 建立以时间命名的文件夹
        SimpleDateFormat sdf1 = new SimpleDateFormat("/yyyy/MM/dd/");
        String datePath = sdf1.format(new Date());
        // 最终真实路径
        String realuUploadBrandPath = realUploadPath + "/doc" + datePath;

        String jcfileName = file.getOriginalFilename();
        String jc = null;
        String alljc = null;
        if (jcfileName.contains("\\[") && jcfileName.contains("\\]")) {
            jc = jcfileName.replaceAll("\\[", "【");
            alljc = jc.replace("\\]", "】");
        } else {
            alljc = jcfileName;
        }
        // 上传文件原始名称
        String jcoriginFileName = new Date().getTime() + "_" + alljc;
        String jcaddress = "/doc" + datePath + jcoriginFileName;

        // 如果路径文件夹不存在就创建
        File dir = new File(realuUploadBrandPath);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        // 新文件
        File jcFile = new File(realuUploadBrandPath + File.separator + jcoriginFileName);
        if (file.getSize() != 0) {
            // 将内存中的文件写入磁盘
            try {
                file.transferTo(jcFile);
            } catch (IllegalStateException | IOException e) {
                e.printStackTrace();
            }
        }
        if (file.getSize() != 0) {
            NoticeFile noticeFile = new NoticeFile();
            noticeFile.setBatch_no(fileNo);
            noticeFile.setAddress(jcaddress);
            noticeFile.setCreate_time(new Date());
            noticeFile.setName(alljc);
            String suffix = alljc.substring(alljc.length() - 4, alljc.length());
            noticeFile.setSuffix(suffix);
            purchaseSimpleNoticeService.addFlie(noticeFile);
        }
    }

    /**
     * 附件修改
     * @param purchaseSimpleNoticeService
     * @param file
     */
    public static void updateFile(PurchaseSimpleNoticeService purchaseSimpleNoticeService,
            MultipartFile file, String fileNo) {
        // 保存附件
        String realUploadPath = "/fphome/sotcbb/webapps/gzfppt/file";
        // 建立以时间命名的文件夹
        SimpleDateFormat sdf = new SimpleDateFormat("/yyyy/MM/dd/");
        String datePath = sdf.format(new Date());
        // 最终真实路径
        String realuUploadBrandPath = realUploadPath + "/doc" + datePath;
        if (file.getSize() != 0) {
            String jcfileName = file.getOriginalFilename();
            String jc = null;
            String alljc = null;
            if (jcfileName.contains("\\[") && jcfileName.contains("\\]")) {
                jc = jcfileName.replaceAll("\\[", "【");
                alljc = jc.replace("\\]", "】");
            } else {
                alljc = jcfileName;
            }
            // 上传文件原始名称
            String jcoriginFileName = new Date().getTime() + "_" + alljc;
            String jcaddress = "/doc" + datePath + jcoriginFileName;
            // 如果路径文件夹不存在就创建
            File dir = new File(realuUploadBrandPath);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            // 新文件
            File jcFile = new File(realuUploadBrandPath + File.separator + jcoriginFileName);
            // 将内存中的文件写入磁盘
            try {
                file.transferTo(jcFile);
            } catch (IllegalStateException | IOException e) {
                e.printStackTrace();
            }

            String batch_no = fileNo;
            NoticeFile noticeFile = purchaseSimpleNoticeService.findFile(batch_no);
            if (noticeFile == null) {
                NoticeFile noticeFile2 = new NoticeFile();
                noticeFile2.setBatch_no(batch_no);
                noticeFile2.setAddress(jcaddress);
                Date create_time = new Date();
                noticeFile2.setCreate_time(create_time);
                noticeFile2.setName(alljc);
                String suffix = alljc.substring(alljc.length() - 4, alljc.length());
                noticeFile2.setSuffix(suffix);
                purchaseSimpleNoticeService.addFlie(noticeFile2);
            } else {
                noticeFile.setAddress(jcaddress);
                noticeFile.setName(alljc);
                String suffix = alljc.substring(alljc.length() - 4, alljc.length());
                noticeFile.setSuffix(suffix);
                purchaseSimpleNoticeService.updatefile(noticeFile);
            }
        }
    }

}

5,存入图片的数据库表SQL,通过BATCH_NO与project表关联

CREATE TABLE `sys_file` (
  `BATCH_NO` varchar(32) NOT NULL COMMENT ‘文件批次号‘,
  `NO` int(11) NOT NULL AUTO_INCREMENT COMMENT ‘编号‘,
  `NAME` varchar(200) DEFAULT NULL COMMENT ‘上传图片名字‘,
  `ADDRESS` varchar(200) NOT NULL COMMENT ‘文件地址‘,
  `SUFFIX` varchar(200) NOT NULL COMMENT ‘文件后缀名称‘,
  `CREATE_TIME` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT ‘创建时间‘,
  `MID_ADDRESS` varchar(200) DEFAULT NULL COMMENT ‘中图路径‘,
  `MIN_ADDRESS` varchar(200) DEFAULT NULL COMMENT ‘小图路径‘,
  PRIMARY KEY (`NO`,`BATCH_NO`) USING BTREE,
  KEY `idx_BATCH_NO_NO` (`BATCH_NO`,`NO`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=188 DEFAULT CHARSET=utf8 ROW_FORMAT=COMPACT COMMENT=‘图片表‘

6,页面查看图片,需要配置一下

https://www.cnblogs.com/ljmm/p/13026342.html

Java上传图片

标签:har   附件   指定   res   ror   default   content   文件写入   jmm   

原文地址:https://www.cnblogs.com/ljmm/p/13176090.html


评论


亲,登录后才可以留言!