springMVC 文件上传

1.在pom.xml文件中添加相关依赖


        
            commons-fileupload
            commons-fileupload
            1.4
        
  1. 在springMVC配置文件中注册文件解析器,同时配置springMVC的静态资源视图解析器,防止前端资源被springMVC的前端控制器拦截
    注意:文件解析器的id必须为multipartResolver否则会报错
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.NullPointerException

    


    

3.编写前端jsp页面

<%@ page contentType="text/html;charset=UTF-8" language="java" %>

    
        文件上传
    
    
        

文件上传页面


5.编写后台Java代码,注意:若使用@RequestParam("upload")注解,则参数需和的name属性值一致,若不使用则MultipartFile参数名必须和前端 的name属性值一致

package com.chen.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * @Description:
 * @author: chenDing
 * @date: 2020/3/6  9:02
 */
@Controller
@RequestMapping("/upload")
public class UploadController {

    @RequestMapping("/testUpload")  //注意MultipartFile参数名必须和前端 的name属性值一致
    public String testUpload(HttpServletRequest request, @RequestParam("upload") MultipartFile upload) {
        String realPath = request.getSession().getServletContext().getRealPath("/upload");
//        String realPath1 = request.getServletContext().getRealPath("/upload");
//        System.out.println(realPath);
//        System.out.println(realPath1);
        File file = new File(realPath);
        if (!file.exists()) {
            file.mkdirs();
        }
        String filename = upload.getOriginalFilename();
//        System.out.println(upload.getName()); /*表单字段name的值 upload*/
        if ("".equals(filename)) {
            return "error.jsp";
        }
        String replace = UUID.randomUUID().toString().replace("-", "");
        filename = replace + "_" + filename;
        try {
            upload.transferTo(new File(realPath,filename));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "success.jsp";
    }
}

测试截图


image.png
image.png
image.png

你可能感兴趣的:(springMVC 文件上传)