使用Springmvc实现文件上传
@RequestMapping(value="/userfilesDownload/{fileId}") public ResponseEntity<byte[]> UserfilesDownload(@RequestParam("file")String file,@PathVariable String fileId,HttpServletRequest request,HttpServletResponse response)throws IOException{ //获得所有请求的路径 String filepath = request.getServletContext().getRealPath("/"); File newfile=null; HttpHeaders headers=null; try{ //filepath+File.separator+file拼接访问路径 ——多出来了一个/crpies newfile=new File(filepath+File.separator+file); //转码 防止文件名乱码 String filename1=new String(filepath.getBytes("utf-8"),"ISO-8859-1"); headers=new HttpHeaders(); //格式化文件 headers.setContentDispositionFormData("attachment", filename1); //用二进制流来下载地址 headers.setContentType(MediaType.APPLICATION_OCTET_STREAM); }catch(Exception e){ throw new RuntimeException(e); } return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(newfile),headers, HttpStatus.OK); }
文件下载
List<Enclosure> fileList=enclosureService.getListByFileIds(fileId); String fileDownUrl=""; String filename=""; for (Enclosure enclosure : fileList) { fileDownUrl=enclosure.getDownloadPath(); filename=enclosure.getName(); } File file = new File(Global.getUserfilesBaseDir() + Global.USERFILES_BASE_URL + fileDownUrl); if (file.exists()) { resp.setContentType("application/force-download");// 设置强制下载不打开 resp.addHeader("Content-Disposition", "attachment;fileName=" + filename);// 设置文件名 byte[] buffer = new byte[1024]; FileInputStream fis = null; BufferedInputStream bis = null; try { fis = new FileInputStream(file); bis = new BufferedInputStream(fis); OutputStream os = resp.getOutputStream(); int i = bis.read(buffer); while (i != -1) { os.write(buffer, 0, i); i = bis.read(buffer); } } catch (Exception e) { e.printStackTrace(); } finally { if (bis != null) { try { bis.close(); } catch (IOException e) { e.printStackTrace(); } } if (fis != null) { try { fis.close(); } catch (IOException e) { e.printStackTrace(); } } } }