springboot实现文件下载和文件上传

旧城等待, 2022-05-27 10:15 441阅读 0赞

1.文件上传功能:直接看controller

  1. @PostMapping("/uploadFile")
  2. public @ResponseBody String singleFileUpload(@RequestParam("file")MultipartFile file){
  3. //判断文件是否为空
  4. if(file.isEmpty()){
  5. return "文件为空,上传失败!";
  6. }
  7. try{
  8. //获得文件的字节流
  9. byte[] bytes=file.getBytes();
  10. //获得path对象,也即是文件保存的路径对象
  11. Path path= Paths.get(FILE_DIR+file.getOriginalFilename());
  12. //调用静态方法完成将文件写入到目标路径
  13. Files.write(path,bytes);
  14. return "恭喜上传成功!";
  15. }catch (IOException e){
  16. e.printStackTrace();
  17. }
  18. return "未知异常";
  19. }

其中FILE_DIR是上传文件的路径,可以自己根据选择设置,比如我这里设置FILE_DIR=”f://file//“ 这个路径

2.文件上传的html页面

  1. <form method="POST" action="/uploadFile" enctype="multipart/form-data">
  2. <input type="file" id="file_input"name="file" /><br/><br/>
  3. <input type="submit" value="Submit" />
  4. </form>

OK,到这里,文件上传功能已经实现,那么现在是文件下载功能

3.直接看文件下载的Controller

  1. @RequestMapping(value="/download",method = RequestMethod.GET)
  2. public void download( HttpServletResponse response){
  3. //要上传的文件名字
  4. String fileName="com.seven.xuanshang.apk";
  5. //通过文件的保存文件夹路径加上文件的名字来获得文件
  6. File file=new File(FILE_DIR,fileName);
  7. //当文件存在
  8. if(file.exists()){
  9. //首先设置响应的内容格式是force-download,那么你一旦点击下载按钮就会自动下载文件了
  10. response.setContentType("application/force-download");
  11. //通过设置头信息给文件命名,也即是,在前端,文件流被接受完还原成原文件的时候会以你传递的文件名来命名
  12. response.addHeader("Content-Disposition",String.format("attachment; filename=\"%s\"", file.getName()));
  13. //进行读写操作
  14. byte[]buffer=new byte[1024];
  15. FileInputStream fis=null;
  16. BufferedInputStream bis=null;
  17. try{
  18. fis=new FileInputStream(file);
  19. bis=new BufferedInputStream(fis);
  20. OutputStream os=response.getOutputStream();
  21. //从源文件中读
  22. int i=bis.read(buffer);
  23. while(i!=-1){
  24. //写到response的输出流中
  25. os.write(buffer,0,i);
  26. i=bis.read(buffer);
  27. }
  28. }catch (IOException e){
  29. e.printStackTrace();
  30. }finally {
  31. //善后工作,关闭各种流
  32. try {
  33. if(bis!=null){
  34. bis.close();
  35. }
  36. if(fis!=null){
  37. fis.close();
  38. }
  39. } catch (IOException e) {
  40. e.printStackTrace();
  41. }
  42. }
  43. }
  44. }

4.接下来是下载功能的html端的实现

  1. <a href="/download">点击下载XX文件</a>

5.至此,文件的upload和download功能已经完成

发表评论

表情:
评论列表 (有 0 条评论,441人围观)

还没有评论,来说两句吧...

相关阅读