文件下载

来源:互联网 发布:淘宝网店海报分辨率 编辑:程序博客网 时间:2024/06/11 15:55
public class DownloadController extends BaseController {    @Autowired    private ResourceService resource;    /**     * 下载文件     * @param urlPath     * @param infoId 信息主键ID     * @param type 1: 可视化  2:基础信息     * @return     */    @RequestMapping("")    public HttpServletResponse download(String urlPath, Integer infoId, Integer type){        try {            response.setContentType("application/x-download");            response.setHeader("Pragma", "public");            response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");            String extName = getImageExtName(urlPath);            OutputStream out = null;            response.addHeader("Content-disposition", "attachment;filename=" + System.currentTimeMillis() + extName);// 设定输出文件头            try {                out = response.getOutputStream();                byte[] imageFromNetByUrl = getImageFromNetByUrl(urlPath);                out.write(imageFromNetByUrl);                out.flush();                // 更新下载次数                if(type ==1 ){                    WhResourceWithBLOBs resource = resource.getResourceById(infoId);                    resource.setDfrDownloadcount(resource.getDfrDownloadcount()+1);                    resourceService.updateResource(resource);                }            } catch (Exception e) {                logger.error(e.getMessage(), e);                throw new Exception("下载失败!");            } finally {                if (out != null) {                    out.close();                }            }        } catch (Exception e) {        }        return null;    }    /**     * 获取文件的拓展名     * @param imgName     * @return     */    public static String getImageExtName(String imgName) {        if (imgName.indexOf(".") < 0) return null;        return imgName.substring(imgName.lastIndexOf("."), imgName.length());    }    /**     * 将url读取成字节数组     * @param strUrl     * @return     */    public static byte[] getImageFromNetByUrl(String strUrl){        try {            URL url = new URL(strUrl);            HttpURLConnection conn = (HttpURLConnection)url.openConnection();            conn.setRequestMethod("GET");            InputStream inStream = conn.getInputStream();            return readInputStream(inStream);        } catch (Exception e) {            e.printStackTrace();        }        return null;    }    /**     * 读取输入流为字节数组     * @param inStream     * @return     * @throws Exception     */    public static byte[] readInputStream(InputStream inStream) throws Exception{        ByteArrayOutputStream outStream = new ByteArrayOutputStream();        byte[] buffer = new byte[1024];        int len = 0;        while ((len = inStream.read(buffer)) != -1) {          outStream.write(buffer, 0, len);        }        inStream.close();        return outStream.toByteArray();    }}