文件操作接口中的http协议头自身编码问题(仅支持ASCLL)

/ 默认分类 / 0 条评论 / 812浏览

文件操作接口中的http协议头自身编码问题(仅支持ASCLL)

下面是一个文件下载的接口:

    @GetMapping("/down/user_template_excel")
    public ResponseEntity<FileSystemResource> downTemplateExcel(String date){
        String fileUrl = "asasasasasa"
        String dateDir = CommonUtil.getFileDirByDate();
        File file = CommonUtil.getFileFromUrl(fileUrl, dateDir + "/" + "用户模板.xlsx", HttpMethod.GET);
        HttpHeaders headers = new HttpHeaders();
        headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
        //设置文件名
        headers.add("Content-Disposition", "attachment; filename=" + CommonUtil.now(Const.yyyyMMdd) + URLEncoder.encode("用户模板") + ".xlsx");
        headers.add("Pragma", "no-cache");
        headers.add("Expires", "0");
        headers.add("Last-Modified", (new Date()).toString());
        headers.add("ETag", String.valueOf(System.currentTimeMillis()));
        return ResponseEntity.ok().headers(headers).contentLength(file.length()).contentType(MediaType.parseMediaType("application/octet-stream")).body(new FileSystemResource(file));
    }

需要注意的是上面标注了设置文件名的那行代码,可以看出这里我将文件名中的中文进行了UrlEncoed编码,之所以这样,是因为header中只支持Ascll,所以当我们使用中文的时候需要将其转为ascll,如果不转那么就会出现乱码。UrlEncode原理其实就是转为ascll然后变为十六进制再每两位加上%。

    public static File getFileFromUrl(String urlPath, String fileFullName, HttpMethod httpMethod) {
        File file;
        try {
            URL url = new URL(urlPath);
            URLConnection urlConnection = url.openConnection();
            HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection;
            httpURLConnection.setConnectTimeout(1000 * 5);
            httpURLConnection.setRequestMethod(httpMethod.name());
            httpURLConnection.setRequestProperty("Charset", "UTF-8");
            httpURLConnection.connect();
            int fileLength = httpURLConnection.getContentLength();
            URLConnection con = url.openConnection();
            BufferedInputStream bin = new BufferedInputStream(httpURLConnection.getInputStream());
            file = new File("/filedir/" + fileFullName);
            if (!file.getParentFile().exists()) {
                file.getParentFile().mkdirs();
            }

            OutputStream out = new FileOutputStream(file);
            int size = 0;
            int len = 0;
            byte[] buf = new byte[2048];
            while ((size = bin.read(buf)) != -1) {
                len += size;
                out.write(buf, 0, size);
            }
            bin.close();
            out.close();
            return file;
        } catch (IOException e) {
            log.error(e.getMessage());
            return null;
        }
    }