下载文件--接口

2022-06-22 00:00:00 文件 下载
@RequestMapping(value = "download",method = RequestMethod.GET)
    public ResponseEntity<byte[]> download(HttpServletResponse response, HttpServletRequest request) throws Exception{

        //预下载文件路径******
        String preDownload_path = "//172.12.34.11/8c2fa5bc-7916-8310-ee65-c77c8a7916ae/TempFile/UploadFile/uploadjob_12796/testlinux总结01.pdf";
        //C:/Users/Administrator/Desktop/Learn/pdf/temp8.pdf
        //C:/Users/Administrator/Desktop/Learn/查询语句.docx
        int index = preDownload_path.lastIndexOf("/");
        //下载后的文件名
        String downloadName = preDownload_path.substring(index+1);
        System.out.println(index);
        System.out.println(downloadName);

        response.setCharacterEncoding("utf-8");
        response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition", "attachment;fileName="+java.net.URLEncoder.encode(downloadName,"UTF-8"));

        InputStream is = null;
        OutputStream os = null;
        try {
            is = new FileInputStream(new File(preDownload_path));
            os = response.getOutputStream();
            byte[] b = new byte[2048];
            int length;
            while ((length = is.read(b)) > 0) {
                os.write(b, 0, length);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            os.close();
            is.close();
        }
        return null;
    }
常见的媒体格式类型如下: 
   text/html : HTML格式
    text/plain :纯文本格式     
    text/xml :  XML格式
    image/gif :gif图片格式   
    image/jpeg :jpg图片格式
    image/png:png图片格式

以application开头的媒体格式类型:
   application/xhtml+xml :XHTML格式
   application/xml     : XML数据格式
   application/atom+xml  :Atom XML聚合格式   
   application/json    : JSON数据格式
   application/pdf       :pdf格式 
   application/msword  : Word文档格式
   application/octet-stream : 二进制流数据(如常见的文件下载)
   application/x-www-form-urlencoded : <form encType=””>中默认的encType,form表单数据被编码为key/value格式发送到服务器(表单默认的提交数据的格式)


另外一种常见的媒体格式是上传文件之时使用的:
   multipart/form-data : 需要在表单中进行文件上传时,就需要使用该格式

 

 

    原文作者:hello_yajing
    原文地址: https://blog.csdn.net/hello_yajing/article/details/107153035
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。

相关文章