在pom.xml中添加的依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
如果使用 thymeleaf模板插件 的话再返回数据时要使用@RestController或者@ResponseBody不然会报错
@Controller
@RequestMapping("/upload2")
public class Fileupandload {
@ResponseBody
@RequestMapping(value = "/shangchuan",method = RequestMethod.POST)
public void upload(@RequestParam MultipartFile file){
String filepath ="D:/graduate2016/";
// 接收上传文件
try{
//首先得到文件
if(!file.isEmpty()){
String filename = file.getOriginalFilename();
//需要给文件修改名称时可以使用 String //fileext=filename.substring(filename.lastIndexOf(".")+1);可以得到源文件的后缀名, 然后再重新命名
filename=filename+"."+fileext;
File dest = new File(filepath ,filename);
file.transferTo(dest);
}else{
throw new Exception("上传文件表单属性应为enctype='multipart/form-data'");
}
// 再修改数据库
}catch(Exception e){
}
}
}
@ResponseBody
@RequestMapping(value ="/xiazai",method = RequestMethod.GET)
public void download(HttpServletRequest request,HttpServletResponse response) throws UnsupportedEncodingException {
//得到全路径的文件名
String filenamewithallpath="";
String tempfilepath="";
if(request.getParameter("filenamewithallpath")!=null){
filenamewithallpath=new String(request.getParameter("filenamewithallpath").getBytes("ISO-8859-1"),"utf-8");//带有全路径的文件名
}
//设置文件路径
File file = new File( filenamewithallpath);
if (file.exists()) {
response.setContentType("application/force-download");// 设置强制下载不打开
response.addHeader("Content-Disposition", "attachment;fileName=" + new String(file.getName().getBytes("UTF-8"),"iso-8859-1")); //new String(file.getName().getBytes("UTF-8"),"iso-8859-1")) 设置文件名,解决中文名乱码的问题
byte[] buffer = new byte[1024];
FileInputStream fis = null;
BufferedInputStream bis = null;
try {
fis = new FileInputStream(file);
bis = new BufferedInputStream(fis);
OutputStream os = response.getOutputStream();
int i = bis.read(buffer);
while (i != -1) {
os.write(buffer, 0, i);
i = bis.read(buffer);
}
System.out.println("success");
} catch (Exception e) {
e.printStackTrace();
} finally {
if (bis != null) {
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
web页面
表单一定要设置为multipart/form-data
<form method="post" action="/upload2/shangchuan" enctype="multipart/form-data">
<input type="file" name="file"><br>
<input type="submit" value="提交">
</form>
<a href = "http://localhost:8081/upload2/xiazai?filenamewithallpath=D://graduate2016/paperblind/20131112002.pdf">下载</a>
在properties中可以对设置上传文件时的一些配置(在网友那直接copy来的)
spring.http.multipart.enabled=true #默认支持文件上传.
spring.http.multipart.file-size-threshold=0 #支持文件写入磁盘.
spring.http.multipart.location= # 上传文件的临时目录
spring.http.multipart.max-file-size=1Mb # 最大支持文件大小
spring.http.multipart.max-request-size=10Mb # 最大支持请求大小