通過檔案url,實現檔案下載
阿新 • • 發佈:2018-12-11
通過url實現檔案下載 @Log("下載檔案") @ResponseBody @RequestMapping(value = "/download", method = RequestMethod.GET) public R Download(HttpServletResponse response,Long id) { String fileUrl = fileService.get(id).getUrl();//檔案url String fileName = fileUrl.substring(fileUrl.lastIndexOf("/")+1);//檔名字 response.setHeader("content-type", "application/octet-stream"); response.setContentType("application/octet-stream"); response.setHeader("Content-Disposition", "attachment;filename=" + fileName); byte[] buff = new byte[1024]; BufferedInputStream bis = null; OutputStream os = null; try { os = response.getOutputStream(); bis = new BufferedInputStream(new URL(fileUrl).openConnection().getInputStream()); int i = bis.read(buff); while (i != -1) { os.write(buff, 0, buff.length); os.flush(); i = bis.read(buff); } } catch (IOException e) { e.printStackTrace(); } finally { if (bis != null) { try { bis.close(); return R.ok(); } catch (IOException e) { e.printStackTrace(); return R.error(); } } } return null; }
R工具類:
import java.util.HashMap; import java.util.Map;
public class R extends HashMap<String, Object> { private static final long serialVersionUID = 1L; public R() { put("code", 0); put("msg", "操作成功"); } public static R error() { return error(1, "操作失敗"); } public static R error(String msg) { return error(500, msg); } public static R error(int code, String msg) { R r = new R(); r.put("code", code); r.put("msg", msg); return r; } public static R ok(String msg) { R r = new R(); r.put("msg", msg); return r; } public static R ok(Map<String, Object> map) { R r = new R(); r.putAll(map); return r; } public static R ok() { return new R(); } @Override public R put(String key, Object value) { super.put(key, value); return this; } }