Vue附件上传,需要用到<el-upload>标签,标签中的属性有很多,对应后台的action,设置上传文件个数及其他设置
在on-success函数中,是上传成功的回调函数,这个地方的处理是后台返回一个文件路径,该标签绑定了一个元素为:nowPersonInfo.filesrc
绑定这个元素的目的是为了再上传的时候,一个表单里还有其他的属性,将这个元素动态绑定以后,存一个文件路径,到时候要取出来的时候再读出来
后台代码:
@PostMapping("/upload") @ResponseBody public void uploadImg(@RequestParam(value="file",required=false)MultipartFile file,HttpServletRequest request, HttpServletResponse resp)throws Exception { if(request.getCharacterEncoding()==null) { request.setCharacterEncoding("UTF-8"); } String fileName=file.getOriginalFilename(); //String suffxName=fileName.substring(fileName.lastIndexOf(".")); String filePath="F://icappImge/"; File dest = new File(filePath + fileName); if (!dest.getParentFile().exists()) { dest.getParentFile().mkdirs(); } try { file.transferTo(dest); ServletOutputStream out=resp.getOutputStream(); OutputStreamWriter ow=new OutputStreamWriter(out,"UTF-8"); ow.write(filePath+fileName); ow.flush(); ow.close(); } catch (IllegalStateException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
OutputStreamWriter会返回前端一个路径,这个路径就是之前绑定元素,上传成功回调函数中的值。
——————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
下载附件的后台代码:
@RequestMapping("/upDown") @ResponseBody public void test(String pk,HttpServletRequest request,HttpServletResponse response) throws Exception{ /* 获取数据库中文件的路径 */ String filePath=service.getFilePath(pk); int inex=filePath.lastIndexOf("/"); String fileName=filePath.substring(inex+1); if(fileName!=null) { String realPath = filePath; File file = new File(realPath); if(file.exists()) { // 配置文件下载 response.setHeader("content-type", "application/octet-stream"); response.setContentType("application/octet-stream"); // 下载文件能正常显示中文 response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8")); byte[] buffer = new byte[1024]; FileInputStream fis = null; BufferedInputStream bis = null; try { fis = new FileInputStream(file); bis = new BufferedInputStream(fis); OutputStream os = response.getOutputStream(); int i = bis.read(buffer); while (i != -1) { os.write(buffer, 0, i); i = bis.read(buffer); } } catch (Exception e) { }finally { if (bis != null) { try { bis.close(); } catch (IOException e) { e.printStackTrace(); } } if (fis != null) { try { fis.close(); } catch (IOException e) { e.printStackTrace(); } } } } } }
传了一个pk,也就是一条数据的主键id,根据id查路径,再去下载,接上一篇文章的附件下载