Java文件上传【通用】

Java文件上传 主要是针对于网页来说,一般是通过input的file类型上传文件流到后台,再通过后台处理将文件移动到指定位置达到上传的目的。
这里贴代码时,主要是以springboot框架为例,但是是通用的。
1、表单提交上传

<form enctype="multipart/form-data" method="post" action="/upload">
    文件:<input type="file" name="fileUpload"/>
    <input type="submit" value="上传"/>
form>
@RequestMapping("/upload")
    public String upload(MultipartFile fileUpload) throws IOException{
        //获取文件名
        String fileName = fileUpload.getOriginalFilename();
        //获取文件后缀名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        //重新生成文件名
        fileName = UUID.randomUUID()+suffixName;
        //指定本地文件夹存储图片
        String filePath = "D:/idea/IdeaProjects/springbootdemo/src/main/resources/static/";
        fileUpload.transferTo(new File(filePath+fileName)); 
        return "index";     
    }

提交表单的话会刷新界面,一般不推荐,但这是比较简单的方法,一般推荐使用ajax提交。

2、ajax提交上传(FormData)

<script>
function uploadHead() {
		var formData = new FormData();
		var file = $('#file')[0].files[0];
		formData.append("upload",file);
		$.ajax({
			url:"/uploadHead",
			async:true,
			processData: false,   // jQuery不要去处理发送的数据
			contentType: false,   // jQuery不要去设置Content-Type请求头
			type:"POST",
			data: formData,
			success:function (data) {
				if(data=="1"){
					alert("上传成功");
				}else{
					alert("上传失败");
				}
			},
			error:function () {
				alert("更新失败");
			},
			dataType:"text"
		});
	}
script>
<input type="file" name="multipartFile" class="fileInput" id="file" >
<input type="button" onclick="uploadHead();">
//我将上传文件做成工具类:
 /**
     * 上传文件
     * @param upload
     * @param path
     * @return
     * @throws IOException
     */
    public String UploadFile(MultipartFile upload,String path) throws IOException {
        //判断该路径是否存在
        File file = new File(path);
        if (!file.exists()) {
            //如果这个文件夹不存在的话,就创建这个文件
            file.mkdirs();
        }
        //获取上传文件名称
        String filename = upload.getOriginalFilename();
        System.out.println(filename);
        //把文件名称设置成唯一值 uuid 以防止文件名相同覆盖
        String uuid = UUID.randomUUID().toString().replace("-", "");
        //新文件名
        filename = uuid + "_" + filename;
        System.out.println(filename);
        //完成文件上传
        upload.transferTo(new File(path, filename));
        String filePath = "upload/" + filename;
        return filePath;
    }

//这里的话是已经将文件上传并即将图片记录在数据库并更换(mybatis)
@RequestMapping("uploadHead")
    public void ReturnHead(HttpServletRequest request, HttpServletResponse response, MultipartFile upload) throws IOException {
        User userSession = (User) request.getSession(true).getAttribute("userSession");
        OperateFile operateFile = new OperateFile();
        if (userSession!=null){
            String path = ResourceUtils.getURL("classpath:").getPath() + "static/upload";
            //System.out.println(path);
            String filePath = operateFile.UploadFile(upload,path);//文件上传成功
            String filename = upload.getOriginalFilename();
            String fileUuid = UUID.randomUUID().toString().replace("-", "");
            Img img = new Img();//进行图片记录
            img.setUuid(fileUuid);
            img.setImg_name(filename);
            img.setImg_type(1);
            img.setImg_path(filePath);
            img.setNote(userSession.getUuid()+"用户上传");
            int c = userService.addImg(img);
            if (c>0){
                User u1 = new User();
                u1.setUuid(userSession.getUuid());
                u1.setImg_uuid(fileUuid);
                int c1 = userService.updateHead(u1);
                if (c1>0){
                    response.getWriter().write("1");
                }else{
                    response.getWriter().write("0");
                }
            }else{
                response.getWriter().write("0");
            }
        }
    }

注意:获取当前项目存储路径的问题

//一般适用,指当前项目下的upload文件夹下
String path = request.getSession().getServletContext().getRealPath("/upload/");

//springboot比较特殊,需要放在static文件夹下路径
String path = ResourceUtils.getURL("classpath:").getPath() + "static/upload";

你可能感兴趣的:(#,SpringBoot,Java,Web,upload,1024程序员节)