fastdfs下載文件重命名

@GetMapping(value = "/download",produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiOperation(value = "文件下載")
    public ResponseEntity<byte[]> download(String fileName, HttpServletRequest request) throws Exception{

        String url = "http://192.168.15.150:8000/group1/M00/00/0VKAbcvBAAFiABXggsY079.doc";
        HttpHeaders headers = new HttpHeaders();

        //處理IE
        String userAgent = request.getHeader("user-agent").toLowerCase();

        if (userAgent.contains("msie") || userAgent.contains("like gecko")  ||
                userAgent.contains("Trident")) {
            // win10 ie edge 瀏覽器 和其他系統的ie
            fileName = URLEncoder.encode(fileName, "UTF-8");
            //解決下載時,空格變加號
            fileName = org.apache.commons.lang3.StringUtils.replace(fileName, "+", "%20");
        } else {
            // fe
            fileName = new String(fileName.getBytes("UTF-8"), "ISO8859-1");

            //解決下載時,空格變加號
            fileName = org.apache.commons.lang3.StringUtils.replace(fileName, "+", "%20");
        }

        //通知瀏覽器以attachment(下載方式)打開圖片
        headers.setContentDispositionFormData("attachment",fileName); //解決原始文件名中有中文出現亂碼);
        //application/octet-stream : 二進制流數據(最常見的文件下載)。
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        return new ResponseEntity<byte[]>(IOUtils.toByteArray(getFileInputStream(url)),
                headers, HttpStatus.CREATED);

    }
    //endregion

    public InputStream getFileInputStream(String urlString) {
        InputStream is = null;
        try {
            // 構造URL
            URL url = new URL(urlString);
            // 打開連接
            URLConnection con = url.openConnection();
            // 輸入流
            is = con.getInputStream();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return is;
    }

兩種方式:一種如上通過輸出流重命名,一種如下通過 Nginx 進行文件重命名

一:在Nginx上進行如下配置,這樣Nginx就會截獲url中的參數attname

if ($arg_attname ~ "^(.+)") {
    #設置下載
    add_header Content-Type application/x-download;
    #設置文件名
    add_header Content-Disposition "attachment;filename=$arg_attname";
}
如下:

二:在url後面增加一個參數,指定原始文件名

url+"?attname="+文件名

如下:

http://192.168.15.150:8000/group1/M00/00/0VKAbcvBAAFiABXggsY079.doc?attname=%E5%8D%B3%E5%BC%80%E7%A5%%98%8E%E7%BB%86-1567649164681.xlsx

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章