springMVC后台如何接受前端上传的文件,与及下载文件
2016-08-18 17:41
351 查看
通过MultipartHttpServletRequest 对象来接受前端上传的文件
下载文件
public static Map<String, Object> upload(HttpServletRequest request) throws IOException{ //文件上传的请求 MultipartHttpServletRequest mRequest = (MultipartHttpServletRequest) request; //获取请求的参数 Map<String, MultipartFile> fileMap = mRequest.getFileMap(); //项目的绝对路径 request.getSession().getServletContext().getRealPath()这个是得到项目的绝对地址 String ctxPath = request.getSession().getServletContext().getRealPath("/") + FileOperateUtil.FILEDIR; File file = new File(ctxPath); if (!file.exists()) { file.mkdir(); } Map<String, Object> result = new HashMap<String, Object>(); Iterator<Map.Entry<String, MultipartFile>> it = fileMap.entrySet().iterator(); //用hasNext() 判断是否有值,用next()方法把元素取出。 while(it.hasNext()){ Map.Entry<String, MultipartFile> entry = it.next(); MultipartFile mFile = entry.getValue(); if(mFile.getSize() != 0 && !"".equals(mFile.getName())){ write(mFile.getInputStream(), new FileOutputStream(ctxPath+mFile.getOriginalFilename())); result.put(mFile.getName(), mFile.getOriginalFilename()); } } return result; }
下载文件
public static void download(HttpServletRequest request, HttpServletResponse response, String storeName, String contentType, String realName) throws Exception { response.setContentType("text/html;charset=UTF-8"); request.setCharacterEncoding("UTF-8"); BufferedInputStream bis = null; BufferedOutputStream bos = null; String ctxPath = request.getSession().getServletContext() .getRealPath("/") + "你的存储的地址"; String downLoadPath = ctxPath + storeName; long fileLength = new File(downLoadPath).length(); response.setContentType(contentType); response.setHeader("Content-disposition", "attachment; filename=" + new String(realName.getBytes("utf-8"), "ISO8859-1")); response.setHeader("Content-Length", String.valueOf(fileLength)); bis = new BufferedInputStream(new FileInputStream(downLoadPath)); bos = new BufferedOutputStream(response.getOutputStream()); byte[] buff = new byte[2048]; int bytesRead; while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) { bos.write(buff, 0, bytesRead); } bis.close(); bos.close(); }
相关文章推荐
- springMVC后台如何接受前端上传的文件,与及下载文件
- 前端文件上传,struts2后台返回json数据,在IE为什么会以文件下载的形式打开。
- 前端接受文件调用后台上传文件的方法
- SpringMVC系列(十一)把后台返回的数据转换成json、文件下载、文件上传
- TELNET 登陆远程机后 如何上传下载文件
- myBatis + SpringMVC上传、下载文件
- linux下如何安装rzsz (配合SecureCRT进行文件上传下载)
- springMVC教程(九)springMVC的文件上传于下载
- 如何使用Flashfxp上传下载文件
- 文件的上传和下载以及如何防止网站被入侵(web开发中很有用的知识)
- 如何上传和下载的网络服务器上的文件
- 探究ftp的奥妙之系统用户如何上传下载文件、vsftpd如何识别证书并利用客户端来实现远程连接传输
- linux下如何使用sftp命令进行文件上传和下载
- SpringMVC中文件上传下载
- linux下如何使用sftp命令进行文件上传和下载
- Java中如何使用组件实现文件上传下载
- 【前端优化】如何将 Internet Explorer 配置为可以同时下载多个文件?
- jsp中如何利用jspsmartupload实现文件上传下载功能
- 文件上传后台和前台代码(文件下载也是)
- 如何在Webstorm/Phpstorm中设置连接FTP,并快速进行文件比较,上传下载,同步等操作