上传:
引入依赖:
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.3</version>
</dependency>
application.xml:
【注意!!!这个bena的id必须为:multipartResolver , 否则上传文件会报400的错误!在这里栽过坑,教训!】
controller方法:
@PostMapping("upload")
@ResponseBody
public R upload(@RequestParam CommonsMultipartFile file) throws Exception{
//获取文件名 : file.getOriginalFilename();
String uploadFileName = file.getOriginalFilename();
System.out.println("上传文件名 : "+uploadFileName);
//上传路径保存设置
String path = "F:/upload";
//如果路径不存在,创建一个
File realPath = new File(path);
if (!realPath.exists()){
realPath.mkdir();
}
System.out.println("上传文件保存地址:"+realPath);
//★★就问香不香,就和你写读流一样
file.transferTo(new File(path+"/"+uploadFileName));
return R.of(ResultCode.SUCCESS);
}
前端上传按钮
<!--不要在开头加"/",你jsp已经写basePath了,so只需写相对于basePath的路径。
"/"默认站点根目录,加了就把真正的站点根目录干掉了-->
<form action="user/upload" method="post" enctype="multipart/form-data">
<input name="username" type="text">
<input name="password" type="password">
<input type="file" name="file">
<input type="submit" value="submit">
</form>
注意:
1.提交方式必须post;
2.enctype=“multipart/form-data”
下载:
配置同上
controller:
@GetMapping("download")
@ResponseBody
public R download(HttpServletResponse response) throws Exception{
String fileName = "楠老师.jpg";
//1、设置response 响应头,处理中文名字乱码问题
response.reset(); //设置页面不缓存,清空buffer
response.setCharacterEncoding("UTF-8"); //字符编码
response.setContentType("multipart/form-data"); //二进制传输数据
//设置响应头,就是当用户想把请求所得的内容存为一个文件的时候提供一个默认的文件名。
//★★★Content-Disposition属性有两种类型:inline 和 attachment
//inline :将文件内容直接显示在页面
//attachment:弹出对话框让用户下载具体例子:
response.setHeader("Content-Disposition",
"attachment;fileName="+ URLEncoder.encode(fileName, "UTF-8"));
//拿到输出流,向浏览器输出
ServletOutputStream outputStream = response.getOutputStream();
//拿到文件输入流
FileInputStream fileInputStream = new FileInputStream("F:ulaod/secondWar.jpg");
byte[] buffer =new byte[1024];
int len;
while((len=fileInputStream.read(buffer))!=-1){
outputStream.write(buffer,0,len);
}
outputStream.flush();;
outputStream.close();
return R.of(ResultCode.SUCCESS);
}