首先是需要配置到springmvc.xml中的配置
<bean name="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="UTF-8"></property>
<property name="maxUploadSize" value="5000000"></property>
</bean>
然后是在controller中的代码:
package com.qq.controller;
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
@Controller
public class FileController {
@RequestMapping("qq")
public String uploadFile(String title,MultipartFile ff) throws Exception {
//System.out.println(title);
//得到的是一个文本文件,如果文件为空,就不需要上传
if(ff.getSize() > 0) {
String filename = ff.getOriginalFilename();
System.out.println(filename+"文件名");
//文件上传的位置
String path = "E:\\file\\";
path += filename;
//文件路径包装成一个file对象
File newfile = new File(path);
//把文件传入到对象中
ff.transferTo(newfile);
}
return "show";
}
/**
* Spring
*
* 通过设置
* @param name
* @return
* @throws Exception
*/
@RequestMapping("downLoad")
public ResponseEntity<byte[]> download(String name) throws Exception{
String path = "E:\\file\\";
path += name;
File file = new File(path);
//http相应头的操作
HttpHeaders headers = new HttpHeaders();
String newname = new String(name.getBytes("UTF-8"),"ISO-8859-1");
headers.setContentDispositionFormData("attachment", newname);;
//设置下载方式
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file), headers, HttpStatus.OK);
}
}