Spring MVC中的(多)文件上传和下载

时间:2019-11-11
本文章向大家介绍Spring MVC中的(多)文件上传和下载,主要包括Spring MVC中的(多)文件上传和下载使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

文件上传

第一步:设置JSP页面表单的属性

action的值为请求地址,method代表请求方式,文件上传的表单的请求方式必须为POST;

enctype="multipart/form-data"是文件上传表单的必要值

<form action="/first/fileupload" method="post" enctype="multipart/form-data"><input type="file" name="file">
    <input type="file" name="file">
    <input type="submit" value="提交">
</form>

第二步:编写控制器方法

方法内第一个参数为前台提交的文件,参数名需要和表单的name一样,不一样的就使用@RequestParam 来设置

@Controller
@RequestMapping("/first")
public class FirstController {
  //文件上传
    @RequestMapping("/fileupload")
    public  String fileUpLoad(@RequestParam MultipartFile[] file, HttpSession session) throws IOException {
        String realPath = session.getServletContext().getRealPath("/img");  //获取target目录下img目录的全路径
    //循环获取每一个文件对象
for (MultipartFile item:file){
       //获取文件原来的名称 String fileName
= item.getOriginalFilename(); File files=new File(realPath,fileName); System.out.println(files);
        //将文件写入到磁盘上.底层调度File的write()方法 item.transferTo(files); }
return "welcome"; } }

第三步:在xml中配置文件上传解析器

bean的id值必须为multipartResolver

    <!--文件上传解析器-->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!--文件上传的字符集-->
        <property name="defaultEncoding" value="UTF-8"></property>
        <!--文件的总大小-->
        <property name="maxUploadSize" value="5000000000"></property>
        <!--单个文件的大小-->
        <property name="maxUploadSizePerFile" value="50000000"></property>
    </bean>

文件下载

  //文件下载
    @RequestMapping("/fileDownLoad")
    public ResponseEntity<byte[]> DownLoad() throws IOException {
        //准备文件
        File file =new File("文件的全路径");
        //中文文件名解决乱码(设置文件的中文名)
        //getBytes()需要抛出或捕获异常
        String filename=new String("下载的文件.txt".getBytes("UTF-8"),"ISO8859-1");
        //设置响应头
        HttpHeaders headers=new HttpHeaders();
        headers.setContentDispositionFormData("attachment",filename);
        //设置内容类型为STREAM流
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        //readFileToByteArray()需要抛出或捕获异常
        return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),headers, HttpStatus.OK);
    }

原文地址:https://www.cnblogs.com/yjc1605961523/p/11834375.html