[学习笔记] SpringMVC之文件上传和下载

# 学习 # · 2021-02-28

使用commons-fileupload实现文件上传

1、导入文件上传的jar包,commons-fileupload , Maven会自动帮我们导入他的依赖包 commons-io包。

<!--文件上传-->
<dependency>
    <groupId>commons-fileupload</groupId>
       <artifactId>commons-fileupload</artifactId>
       <version>1.3.3</version>
</dependency>
<!--servlet-api导入高版本的-->
<dependency>
       <groupId>javax.servlet</groupId>
       <artifactId>javax.servlet-api</artifactId>
       <version>4.0.1</version>
</dependency>

2、配置bean:multipartResolver(id名必须为这个)。

<!--文件上传配置-->
<bean id="multipartResolver"  class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
       <!-- 请求的编码格式,必须和jSP的pageEncoding属性一致,以便正确读取表单的内容,默认为ISO-8859-1 -->
       <property name="defaultEncoding" value="utf-8"/>
       <!-- 上传文件大小上限,单位为字节(10485760=10M) -->
       <property name="maxUploadSize" value="10485760"/>
       <property name="maxInMemorySize" value="40960"/>
</bean>

3、编写前端页面:

<!--
    注意enctype="multipart/form-data"
-->
<form action="/upload" enctype="multipart/form-data" method="post">
     <input type="file" name="file"/>
     <input type="submit" value="upload">
</form>

4、编写Controller:

@Controller
public class FileController {
    //@RequestParam("file") 将name=file控件得到的文件封装成CommonsMultipartFile 对象
       //批量上传CommonsMultipartFile则为数组即可
       @RequestMapping("/upload")
       public String fileUpload(@RequestParam("file") CommonsMultipartFile attach , HttpServletRequest request) throws IOException {
        //定义文件上传目录
        String path = request.getServletContext().getRealPath("/upload");

        //获取原文件名:file.getOriginalFilename();
           String oldFileName = attach.getOriginalFilename();

        //获取原文件名后缀
        String prefix = FilenameUtils.getExtension(oldFileName);

        //定义可上传文件大小并进行验证
        int filesize = 500000;    //500k
        if(attach.getSize() >  filesize){
            request.setAttribute("uploadFileError", "上传大小不得超过 500k!");
            return "index";
        } else if(prefix.equalsIgnoreCase("jpg") || prefix.equalsIgnoreCase("png")){
                //对图片格式进行验证

                //定义新的图片名
                String fileName = System.currentTimeMillis()+RandomUtils.nextInt(1000000)+"_Personal.jpg";

                File targetFile = new File(path, fileName);
                if(!targetFile.exists()){
                    targetFile.mkdirs();
                }

                //保存文件
                try {
                    attach.transferTo(targetFile);
                } catch (Exception e) {
                    e.printStackTrace();
                    request.setAttribute("uploadFileError", "上传失败!");
                    return "index";
                }
                //上传后的文件地址
                String idPicPath = path + File.separator + fileName;
            } else {
                request.setAttribute("uploadFileError", "上传图片格式不正确");
                return "index";
            }
        }
      }
}

5、测试上传文件。


文件下载

1、修改Controller:

@RequestMapping(value="/download")
public String downloads(HttpServletResponse response ,HttpServletRequest request) throws Exception{
       //要下载的图片地址
       String  path = request.getServletContext().getRealPath("/upload");
       String  fileName = "基础语法.jpg";

       //1、设置response 响应头
       response.reset(); //设置页面不缓存,清空buffer
       response.setCharacterEncoding("UTF-8"); //字符编码
       response.setContentType("multipart/form-data"); //二进制传输数据
       //设置响应头
       response.setHeader("Content-Disposition", "attachment;fileName="+URLEncoder.encode(fileName, "UTF-8"));

       File file = new File(path,fileName);

    //2、 读取文件:输入流
       InputStream input=new FileInputStream(file);

    //3、 写出文件:输出流
       OutputStream out = response.getOutputStream();

       byte[] buff =new byte[1024];
       int index=0;

       //4、执行写出操作
       while((index= input.read(buff))!= -1){
           out.write(buff, 0, index);
           out.flush();
      }
       out.close();
       input.close();
       return null;
}

2、前端设置一个下载按钮:

<a href="/download">点击下载</a>
如无特殊说明,本博所有文章均为博主原创。

如若转载,请注明出处:一木林多 - https://www.l5v.cn/archives/252/

评论