前言 
上传文件和下载文件是我们平时经常用到的功能,接下来就让我们用SpringBoot,Vue3和ElementPlus组件实现文件的上传和下载功能吧~  
上传前端页面 
前端页面我们可以使用ElementPlus框架的el-upload组件完成上传,主要的参数解释如下:  
- action属性:指定请求的url
 - onsuccess属性: 请求成功后的回调函数
  我们可以使用axios向后端发起get请求,然后后端返回文件保存的位置   
表单项上传框代码如下:  
<el-form-item label="上传图片" ref="uploadElement">
    <el-upload
        class="upload-demo"
        action="/api/file/uploadFile"
        :limit="5"
        :on-success="uploadFileSuccess" 
    >
        <el-button type="primary">添加附件</el-button>
        <template #tip>
            <div class="el-upload__tip">
                pdf, md, word格式均可
            </div>
        </template>
    </el-upload>
</el-form-item>
  
js单击事件代码如下  
uploadFileSuccess(response, file, fileList) {
    let filePath = response.data;
    
    alert(response.data);
    
    this.attachForm.downloadUrl = filePath;
}
  
上传后端代码 
Controller代码如下:  
@PostMapping("/uploadFile")
public String uploadFile(@RequestParam("file") MultipartFile file, HttpServletRequest request) throws IllegalStateException, IOException{
    
    String path = "D:\\uploadfiles";
    String result = "";
    
    result = fileService.storeFile(file, path);
    logger.info("文件已保存至" + result);
    return result;
}
  
fileService代码如下:  
@Override
public String storeFile(MultipartFile file, String path) throws IllegalStateException, IOException {
    
    String fileName = file.getOriginalFilename();
    
    
    
    
    
    File filePath = new File(path + File.separator + fileName);
    
    if (!filePath.getParentFile().exists()) {
        filePath.getParentFile().mkdirs();
    }
    
    file.transferTo(filePath);
    
    logger.info("文件已保存至" +filePath.toString());
    return filePath.toString();
}
  
下载后端代码 
- 因为下载的是文件,所以我们要指定
content-type为"application/octet-stream;charset=utf-8"。 - 当文件名中含有中文字符时,需要使用
URLEncoder.encode(fileName, "UTF-8")转码,然后在前端在转回来,否则会乱码。   
@RequestMapping("/downloadFile")
public void downloadFiles(@RequestParam("file") String downUrl, HttpServletRequest request, HttpServletResponse response){
  OutputStream outputStream=null;
  InputStream inputStream=null;
  BufferedInputStream bufferedInputStream=null;
  byte[] bytes=new byte[1024];
  File file = new File(downUrl);
  String fileName = file.getName();
  logger.info("本次下载的文件为" + downUrl);
  
  try {
      
      
      response.setHeader("Content-Disposition", "attachment;filename=" +  URLEncoder.encode(fileName, "UTF-8"));
      
      response.setContentType("application/octet-stream;charset=utf-8");
      inputStream = new FileInputStream(file);
      bufferedInputStream = new BufferedInputStream(inputStream);
      outputStream = response.getOutputStream();
      int i = bufferedInputStream.read(bytes);
      while (i!=-1){
          outputStream.write(bytes,0,i);
          i = bufferedInputStream.read(bytes);
      }
  } catch (IOException e) {
      e.printStackTrace();
  }finally {
      try {
          if (inputStream!=null){
              inputStream.close();
          }
          if (outputStream!=null){
              outputStream.close();
          }
          if (bufferedInputStream!=null){
              bufferedInputStream.close();
          }
      } catch (IOException e) {
          e.printStackTrace();
      }
  }
  
下载前端代码 
- 为了让浏览器弹出下载提示框,我们需要在前端做一下处理。
 -  
   
   
downloadAttach(url) {
    let _this = this;
    
    this.$axios
    .get('/api/file/downloadFile', {
        params: {
            
            file: url,
        }
    })
    .then(res => {
        
        console.log(res.data); 
        let blob = new Blob([res.data])
        let contentDisposition = res.headers['content-disposition']
        let pattern = new RegExp('filename=([^;]+\\.[^\\.;]+);*')
        let result = pattern.exec(contentDisposition)
        
        let fileName = decodeURI(result[1])
        let downloadElement = document.createElement('a')
        
        let href = window.URL.createObjectURL(blob)
        downloadElement.style.display = 'none'
        downloadElement.href = href
        
        downloadElement.download = fileName
        document.body.appendChild(downloadElement)
        
        downloadElement.click()
        
        document.body.removeChild(downloadElement)
        
        window.URL.revokeObjectURL(href)
    })
    .catch(() => {
        alert("请求出错");
    })
    
}
  
总结 
上传下载文件中最让我头疼的是文件名包含中文问题,原先一直不了解不同字符集之间的区别,现在终于清楚点了,原来汉字在电脑里有一种单独地唯一的存储格式,称为内部码。我们使用不同的字符集(如GBK,UTF-8)进行编码和解码时,只是在以不同的方式存储这些内部码,以字节的形式存储下来。  
参考文献 
下载文件时文件名含有中文乱码问题  Unicode、UTF-8 和 ISO8859-1到底有什么区别 
                
                
                
        
        
    
  
 
 |