springMVC上传文件和文件下载

springMVC.xml文件

 

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

//需要导入fileupload包

<dependency>
     <groupId>commons-fileupload</groupId>
     <artifactId>commons-fileupload</artifactId>
     <version>1.3.1</version>
</dependency>
 <dependency>
     <groupId>commons-io</groupId>
     <artifactId>commons-io</artifactId>
     <version>2.4</version>
</dependency>

 

1) 上传单个文件

页面:

<form action="${pageContext.request.contextPath}/upload/uploadFile" method="post" enctype="multipart/form-data">
    <input type="file" name="imgFile"/>
    <input type="submit" value="提交">
</form>

controller

@RequestMapping(value="uploadFile")
public String uploadFile(MultipartFile imgFile, HttpSession session) throws IllegalStateException, IOException{
    if(imgFile.getSize()==0){
     //没有上传文件
     return error;
   }
  
//获取文件名称: temp.jpg String oFilename = imgFile.getOriginalFilename();
   String path = session.getServletContext().getRealPath("/productImages"); //上传文件保存目录
//设置随机名称,防止文件名称重名 String uuidFilename = UUID.randomUUID().toString().replace("-", "") + oFilename.substring(oFilename.lastIndexOf(".")); imgFile.transferTo(new File(path, uuidFilename)); return "success"; }

2) 上传多个文件

页面:

<form action="${pageContext.request.contextPath}/upload/uploadFiles" method="post" enctype="multipart/form-data">
    <input type="file" name="imgFiles"/>
    <input type="file" name="imgFiles"/>
    <input type="file" name="imgFiles"/>
    <input type="submit" value="提交">
</form>

UploadVo

import java.util.List;
import org.springframework.web.multipart.MultipartFile;
public class UploadVo { private List<MultipartFile> imgFiles; public List<MultipartFile> getImgFiles() { return imgFiles; } public void setImgFiles(List<MultipartFile> imgFiles) { this.imgFiles = imgFiles; } }

controller

@RequestMapping(value="uploadFiles")
public String uploadFiles(UploadVo vo) throws IllegalStateException, IOException{
     //获取上传图片文件集合
     List<MultipartFile> imgFiles = vo.getImgFiles();
        
     for (MultipartFile multipartFile : imgFiles) {
            
         if(multipartFile.getSize() <= 0 ){//文件大小为0,跳过
             continue;
         }
         //获取文件名称
         String filename = multipartFile.getOriginalFilename();
         //生成随机文件名
         String uuidFilename = UUID.randomUUID().toString().replace("-", "")+filename.substring(filename.lastIndexOf("."));
         //将文件写入磁盘中
         multipartFile.transferTo(new File("d:/" + uuidFilename));
     }
     return "test";
}

 文件下载

页面:

<a href="${pageContext.request.contextPath}/upload/download?filename=文件12.jpg">下载文件</a>

controller:

//下载文件
@RequestMapping(value="/download")
public ResponseEntity<byte[]> download(@RequestParam("filename") String filename) throws IOException{
        
    //下载显示的文件名,解决中文名称乱码问题
    String downloadFilename = new String(filename.getBytes("iso8859-1"), "utf-8");
    //创建文件
    File file = new File("d:/", downloadFilename);
        
     if(!file.exists()){
          //文件不存在
         return null;
     }
        
    //创建请求头
    HttpHeaders headers = new HttpHeaders();
        
    //通知浏览器以attachment(下载方式)打开图片
     headers.setContentDispositionFormData("attachment", filename);
        
     //application/octet-stream : 二进制流数据(最常见的文件下载)
     headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        
     //返回ResponseEntity<byte[]>
     return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file), headers, HttpStatus.CREATED);
}

 

posted @ 2018-06-19 18:11  Aaron2705  阅读(132)  评论(0编辑  收藏  举报