JAVA文件上传和下载
上传和下载i
·
1.文件上传
<!--文件上传-->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.3</version>
</dependency>
配置bean:multipartResolver
【注意!!!这个bena的id必须为:multipartResolver , 否则上传文件会报400的错误!在这里栽过坑,教训!】
<!--文件上传配置-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 请求的编码格式,必须和jSP的pageEncoding属性一致,以便正确读取表单的内容,默认为ISO-8859-1 -->
<property name="defaultEncoding" value="utf-8"/>
<!-- 上传文件大小上限,单位为字节(10485760=10M) -->
<property name="maxUploadSize" value="10485760"/>
<property name="maxInMemorySize" value="40960"/>
</bean>
CommonsMultipartFile 的常用方法:
- String getOriginalFilename():获取上传文件的原名
- InputStream getInputStream():获取文件流
- void transferTo(File dest):将上传文件保存到一个目录文件中
/** * 类描述: * * @author czh * @version 1.0 * @date 2022/5/31 19:01 */ @RestController public class UploadController { @PostMapping("upload") public R upload(@RequestParam("file") CommonsMultipartFile file) throws Exception { String format = DateTimeFormatter.ofPattern("yyyy-MM-dd").format(LocalDateTime.now()); // 文件夹路径 String path = Constant.PATH + format; // 判断是否有这个文件夹 没有的话新建 File file1 = new File(path); if(!file1.exists()){ file1.mkdirs(); } // 新的文件名 String newFile = UUID.randomUUID().toString() + file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")); // 文件元数据 MyFile myFile = new MyFile(); myFile.setSize(file.getSize()); myFile.setOriginalFilename(file.getOriginalFilename()); myFile.setUrl(path + "/" + newFile); file.transferTo(new File(path + "/" + newFile)); return R.returnSuccess("上传成功"); } }
2.文件下载
-
第一种可以直接向response的输出流中写入对应的文件流
-
第二种可以使用 ResponseEntity<byte[]>来向前端返回文件
1、传统方式
@GetMapping("/download1")
@ResponseBody
public R download1(HttpServletResponse response){
FileInputStream fileInputStream = null;
ServletOutputStream outputStream = null;
try {
// 这个文件名是前端传给你的要下载的图片的id
// 然后根据id去数据库查询出对应的文件的相关信息,包括url,文件名等
String fileName = "ceshi.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"));
// 通过url获取文件
File file = new File("D:/upload/"+fileName);
fileInputStream = new FileInputStream(file);
outputStream = response.getOutputStream();
byte[] buffer = new byte[1024];
int len;
while ((len = fileInputStream.read(buffer)) != -1){
outputStream.write(buffer,0,len);
outputStream.flush();
}
return R.success();
} catch (IOException e) {
e.printStackTrace();
return R.fail();
}finally {
if( fileInputStream != null ){
try {
fileInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if( outputStream != null ){
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
2、使用ResponseEntity
@GetMapping("/download2")
public ResponseEntity<byte[]> download2(){
try {
String fileName = "ceshi.jpg";
byte[] bytes = FileUtils.readFileToByteArray(new File("D:/upload/"+fileName));
HttpHeaders headers=new HttpHeaders();
// Content-Disposition就是当用户想把请求所得的内容存为一个文件的时候提供一个默认的文件名。
headers.set("Content-Disposition","attachment;filename="+ URLEncoder.encode(fileName, "UTF-8"));
headers.set("charsetEncoding","utf-8");
headers.set("content-type","multipart/form-data");
ResponseEntity<byte[]> entity=new ResponseEntity<>(bytes,headers, HttpStatus.OK);
return entity;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
更多推荐
已为社区贡献1条内容
所有评论(0)