Springmvc 服务器端文件下载 笔记

业务场景:点击下载后直接保存而不是打开

解决代码:前端传入url

/**
     * 返回流
     * 
     * @param requestMap 请求参数
     * @param response 返回对象
     */
    @RequestMapping(value = "/file2Stream", method = RequestMethod.GET)
    public void file2Stream(@Json Map<String, Object> requestMap, HttpServletResponse response) {
        InputStream iStream = null;
        OutputStream outStrem = null;
        try {
            String url = String.valueOf(requestMap.get("url"));
            iStream = getFileStream(url);
            String fileName = String.valueOf(requestMap.get("fileName"));
            fileName = new String(fileName.getBytes(), "ISO8859-1");
            response.setCharacterEncoding("utf-8");
            response.setContentType("multipart/form-data");
            response.setHeader("Content-Disposition", "attachment;filename=\"" + fileName + "\"");
            outStrem = response.getOutputStream();
            outStrem.write(StreamUtils.getBytes(iStream));
            outStrem.flush();
        } catch (Exception e) {
            LOG.error("ProductSalesRecommendController.file2Stream  error | ({})", e);
        }finally {
            if(iStream != null){
                try {
                    iStream.close();
                    iStream = null;
                } catch (IOException e) {
                    LOG.error("file2Stream.InputStream.close  error | ({})", e);
                }
            }
            if(outStrem != null){
                try {
                    outStrem.close();
                    outStrem = null;
                } catch (IOException e) {
                    LOG.error("file2Stream.OutputStream.close  error | ({})", e);
                }
            }
        }
    }
/**
     * HttpClient获取网络路径的文件流
     * 
     * @param url 链接字符串
     * @return InputStream
     * @throws IllegalStateException
     * @throws IOException
     */
    private InputStream getFileStream(String url)
            throws IllegalStateException, IOException {
        InputStream inStream = new URL(url).openStream();
        return inStream;
    }
Solver : fage



猜你喜欢

转载自blog.csdn.net/boneix/article/details/51303280