SpringBoot框架上傳文件及下載文件(解決下載中文文件名亂碼問題!!!)


***上傳文件***

@PostMapping(value = "/fileUpload")
    public R fileUpload(@RequestParam(value = "file") MultipartFile file,Long id) {
        if (file.isEmpty()) {
            System.out.println("文件為空");
        }
        // 文件名
        String fileName = file.getOriginalFilename();
        assert fileName != null;
        // 后綴名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        // 上傳后的路徑
        String filePath = "D://gzagis-file//facility-file//";
        // 新文件名
        fileName =id + suffixName;
        File dest = new File(filePath + fileName);
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }
        try {
            file.transferTo(dest);
        } catch (IOException e) {
            e.printStackTrace();
        }
        facilityService.update(Wrappers.<Facility>update().set("file_path",filePath+fileName).eq("id",id));
        return R.ok().message("上傳文件成功!");
    }

 

***下載文件***

public static void download(String path,HttpServletResponse response,HttpServletRequest request){
        try {
            // path是指想要下載的文件的路徑
            File file = new File(path);
            // 獲取文件名
            String filename = file.getName();
            // 獲取文件后綴名
            String ext = filename.substring(filename.lastIndexOf(".") + 1).toLowerCase();
            // 將文件寫入輸入流
            FileInputStream fileInputStream = new FileInputStream(file);
            InputStream fis = new BufferedInputStream(fileInputStream);
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            // 清空response
            response.reset();
            // 設置response的Header
            response.setContentType("text/html;charset=utf-8");
            //Content-Disposition的作用:告知瀏覽器以何種方式顯示響應返回的文件,用瀏覽器打開還是以附件的形式下載到本地保存
            //attachment表示以附件方式下載   inline表示在線打開   "Content-Disposition: inline; filename=文件名.mp3"
            // filename表示文件的默認名稱,因為網絡傳輸只支持URL編碼的相關支付,因此需要將文件名URL編碼后進行傳輸,前端收到后需要反編碼才能獲取到真正的名稱
            filename=filenameEncoding(filename,request);
            response.addHeader("Content-Disposition", "attachment;filename=" + filename);
            // 告知瀏覽器文件的大小
            response.addHeader("Content-Length", "" + file.length());
            OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/octet-stream");
            outputStream.write(buffer);
            outputStream.flush();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    public static String filenameEncoding(String filename, HttpServletRequest request) throws UnsupportedEncodingException {
        // 獲得請求頭中的User-Agent
        String agent = request.getHeader("User-Agent");
        // 根據不同的客戶端進行不同的編碼

        if (agent.contains("MSIE")) {
            // IE瀏覽器
            filename = URLEncoder.encode(filename, "utf-8");
        } else if (agent.contains("Firefox")) {
            // 火狐瀏覽器
            BASE64Encoder base64Encoder = new BASE64Encoder();
            filename = "=?utf-8?B?" + base64Encoder.encode(filename.getBytes("utf-8")) + "?=";
        } else {
            // 其它瀏覽器
            filename = URLEncoder.encode(filename, "utf-8");
        }
        return filename;
    }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM