SpringBoot如何实现文件上传和下载

旧城等待, 2021-06-12 20:36 676阅读 0赞

文件上传

其实文件上传无非就是文件的读取和写入,明白这个道理之后就好办了。
前端页面

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

这里需要注意的就是表单的enctype属性值必须设置为multipart/form-data
后端Controller

  1. public static final String FILEPATH="E://wunian/test.txt";
  2. @PostMapping("/fileUpload")
  3. public @ResponseBody String fileUpload(@RequestParam("myFile")MultipartFile file){
  4. //判断文件是否为空
  5. if(file.isEmpty()){
  6. return "请不要上传空文件!";
  7. }
  8. try{
  9. //获得文件的字节流
  10. byte[] bytes=file.getBytes();
  11. //获得文件保存的路径对象
  12. Path path= Paths.get(FILEPATH+file.getOriginalFilename());
  13. //将文件写入到目标路径中
  14. Files.write(path,bytes);
  15. return "文件上传成功!";
  16. }catch (IOException e){
  17. e.printStackTrace();
  18. }
  19. return "文件上传失败!";
  20. }

从上面代码中可以看出,我们只需要将上传文件的类型定义成MultipartFile对象即可传入,然后通过一些文件操作API读取文件数据再写入到目标路径即可。

文件下载

前端页面

  1. <a href="/download">立即下载</a>

后端Controller

  1. public static final String FILEPATH="E://wunian/test.txt";
  2. @RequestMapping(value="/download",method = RequestMethod.GET)
  3. public void download( HttpServletResponse response){
  4. //下载文件名
  5. String fileName="test.txt";
  6. //通过文件的保存文件夹路径加上文件的名字来获得文件
  7. File file=new File(FILEPATH,fileName);
  8. if(file.exists()){ //判断文件是否存在
  9. //设置响应的内容格式,force-download表示只要点击下载按钮就会自动下载文件
  10. response.setContentType("application/force-download");
  11. //设置头信息,filename表示前端下载时的文件名
  12. response.addHeader("Content-Disposition",String.format("attachment; filename=\"%s\"", file.getName()));
  13. //进行读写操作
  14. byte[] buffer=new byte[1024];
  15. FileInputStream fileInputStream=null;
  16. BufferedInputStream bufferedInputStream=null;
  17. try{
  18. fileInputStream=new FileInputStream(file);
  19. bufferedInputStream=new BufferedInputStream(fileInputStream);
  20. //获取输出流
  21. OutputStream os=response.getOutputStream();
  22. //读取并且写入文件到输出流
  23. int i=bufferedInputStream.read(buffer);
  24. while(i!=-1){
  25. os.write(buffer,0,i);
  26. i=bufferedInputStream.read(buffer);
  27. }
  28. }catch (IOException e){
  29. e.printStackTrace();
  30. }finally {
  31. //关闭输入输出流
  32. try {
  33. if(bufferedInputStream!=null){
  34. bis.close();
  35. }
  36. if(fileInputStream!=null){
  37. fileInputStream.close();
  38. }
  39. } catch (IOException e) {
  40. e.printStackTrace();
  41. }
  42. }
  43. }
  44. }

从上面代码中可以看出,下载和上传一样,本质上也是流的输入输出,不过不同的是下载需要设置response的头信息和内容格式,而且头信息一般设置为Content-Disposition=attachment; filename=xxx

发表评论

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

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

相关阅读