SpringMVC文件上传

第一步:加入依赖包
commons-fileupload, commons-io


    
        commons-fileupload
        commons-fileupload
        1.3.1
    
    
        commons-io
        commons-io
        2.4
    

第二步:开发上传页面
页面添加
method="post" enctype="multipart/form-data"

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


Title



我的姓名:

我的照片:




第三步:配置文件类型解析器

在applicationContext.xml里面加入配置:



    
    

源码:


SpringMVC文件上传_第1张图片
image.png

第四步:开发Controller

普通参数可用request接受,文件参数用MultipartFile接受并使用注解
@RequestParam("singleupload")页面对应的文件名称

业务代码:先判断在WEB-INF底下是否有upload文件夹,如果不存在的话,新建文件夹,最后将刚刚上传的文件直接存在WEB-INF目录底下的upload文件夹下。

    @RequestMapping("uploadsingle.do")
    public String goTioSingleUpload(Model model,HttpServletRequest request,@RequestParam("singleupload") MultipartFile multipartFile){
        String username = request.getParameter("username");
        String originalFilename = multipartFile.getOriginalFilename();

        String realPath = request.getServletContext().getRealPath("/WEB-INF/upload/");
        File file =new File(realPath);
        if(!file.exists()){
            file.mkdirs();
        }
        File filedir =new File(realPath+originalFilename);
        System.out.println(filedir.getAbsolutePath());
        try {
            multipartFile.transferTo(filedir);
        } catch (IOException e) {
            e.printStackTrace();
        }
        model.addAttribute("path",filedir.getAbsolutePath());
        return "/index.jsp";
    }

打印输出 :

控制台以及界面分别输出上传文件的路径:


SpringMVC文件上传_第2张图片
image.png
SpringMVC文件上传_第3张图片
image.png

观察磁盘目录,发现此文件在打印输出的文件夹内。


SpringMVC文件上传_第4张图片
image.png

第五步:多文件上传(扩展)
多文件上传(页面上传控件名称一致):
@RequestParam(“imgs") CommonsMultipartFile files[]

前端界面:

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


Title



我的姓名:

我的照片1:

我的照片2:

我的照片3:

我的照片4:




imgs.do 如下:
@RequestMapping("/imgs.do")
public String goImgs(Model model,HttpServletRequest request,@RequestParam("imgs") CommonsMultipartFile[] files){
String realPath = request.getServletContext().getRealPath("/WEB-INF/upload/");
File file2 = new File(realPath);
StringBuffer stringBuffer =new StringBuffer();
if(!file2.exists()){
file2.mkdirs();
}
for (CommonsMultipartFile file : files) {
String originalFilename = file.getOriginalFilename();
File file1 =new File(realPath+originalFilename);
stringBuffer.append(file1.getAbsolutePath()).append("&");
try {
file.transferTo(file1);
} catch (IOException e) {
e.printStackTrace();
}
}
model.addAttribute("imgs",stringBuffer);
return "/index.jsp";
}
注意下面的两个箭头 ,当我们上传文件的时候,我们将所有上传的文件绝对路径进行拼接,之后将字符串拼接转发给index.jsp

SpringMVC文件上传_第5张图片
image.png

演示效果:
SpringMVC文件上传_第6张图片
image.png

SpringMVC文件上传_第7张图片
image.png

注意:
这里有一个问题 当我们再次上传相同的文件的时候 ,发现并没有再次添加,观察文件的修改时间,发现修改时间正好为第二次上传的时间,这也就说明了 ,添加相同名称的文件属于更新文件目录的文件。

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