文件上传与下载
1. 文件上传
关键代码:
public void save(File cenclosure,Collectfile collectfile) { try { InputStream inputStream = new FileInputStream(cenclosure); collectfile.setCenclosure(inputStream); String name = cenclosure.getName(); collectfile.setCmenclosure(name); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } if (Validation.hasErrors()) { this.printError(Validation.getErrorsAsString()); return; } collectfileService.save(collectfile); }
注意事项:
1.其中参数 cenclosure 要和前端form表单中的参数名称一致,否则无法上传
2.将File类型转换成流的形式,数据库中以二进制的形式存储
2. 文件下载
关键代码:
/** * 文件下载 * @param omenclosure 文件名 * @throws IOException */ public void downloadLocal(String id){ try { //根据编号查询得到实体类对象 Collectfile collectfile = (Collectfile) collectfileService.findById(id); HttpServletResponse response = response(); //获取InputStrem流 InputStream in = collectfile.getCenclosure(); response.setContentType("application/x-msdownload"); response.addHeader("Content-Disposition", "attachment; filename="+new String(collectfile.getCmenclosure().getBytes("gb2312"),"iso-8859-1")); OutputStream out =response.getOutputStream(); byte[] b = new byte[1024]; int l; while((l = in.read(b)) != -1){ out.write(b, 0, l); } in.close(); out.flush(); out.close(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } }