文件上传 、下载 、将文件发送到浏览器
1.上传 @PostMapping("/upload") @ResponseBody public R upload(@RequestParam("file") CommonsMultipartFile file, HttpServletRequest request) throws Exception{ //获取文件名 : file.getOriginalFilename(); String uploadFileName = file.getOriginalFilename(); System.out.println("上传文件名 : "+uploadFileName); //上传路径保存设置 String path = "D:/upload"; //如果路径不存在,创建一个 File realPath = new File(path); if (!realPath.exists()){ realPath.mkdir(); } System.out.println("上传文件保存地址:"+realPath); file.transferTo(new File(path+"/"+uploadFileName)); return R.success(); }
2.下载
@GetMapping("/download") @ResponseBody public R download1(HttpServletResponse response){ FileInputStream fileInputStream = null; ServletOutputStream outputStream = null; try { // 这个文件名是前端传给你的要下载的图片的id // 然后根据id去数据库查询出对应的文件的相关信息,包括url,文件名等 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")); // 通过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(); } } } }
3.将文件发送到浏览器
FileInputstream fis = new FileInputstream (file) ;
BufferedInputstream bis = new BufferedInputstream (fis ) ;
byte[] bytes = new byte [ bis.available ( ) ];
response.setcontentType ( contentType) ;
outputstream os = response.getoutputstream ( );
bis.read(bytes) ;
os.write (bytes) ;
首先要读取该文件作为 FileInputStream,并将内容加载到一个字节数组。随后,获取HttpServletResponse的OutputStream,并调用其 write方法传入字节数组。
使用Files.copy()方法:
Path file = Paths.get ( .. . ) ;
Files.copy(file,response.getoutputstream ( ) ) ;
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?