java web上传文件和下载文件代码片段分享
本文实例为大家分享了java web上传文件和下载文件的具体代码,供大家参考,具体内容如下
/** * Purpose:上传文档 * * @param req * @param fileTitle * @param fileType * @param fileDesc * @return */ @RequestMapping("upload") public ModelAndView upload(HttpServletRequest req, String fileType, String fileDesc, String share) { UserAllInfo userAll = (UserAllInfo) req.getSession().getAttribute("userAll"); ModelAndView mav = new ModelAndView(); // 获取文件的大小 String fileSize = ""; int length = req.getContentLength(); //转换成KB double len1 = (double) (Math.round((length / 1024) * 100)) / 100; //转换成MB double len2 = (double) (Math.round((len1 / 1024) * 100)) / 100; if (len2 > 1) { fileSize = String.valueOf(len2) + "MB"; } else { fileSize = String.valueOf(len1) + "KB"; } //将请求转换成处理文件的请求 MultipartRequest mreq = (MultipartRequest) req; //文件上传专用类 MultipartFile mfile = mreq.getFile("uploadFile"); // 得到上下文路径 String root = req.getSession().getServletContext().getRealPath("/"); File dir = new File(root); // 获取文件名和文件的mime类型 String str = mfile.getOriginalFilename(); String[] st = str.split("\\."); File savedFile = null; try { //在指定目录中创建一个新的空文件,文件名称加前缀"upload_" savedFile = File.createTempFile("upload_", mfile.getOriginalFilename(), dir); //将缓冲区的内容复制到新创建的文件中 FileCopyUtils.copy(mfile.getInputStream(), new FileOutputStream(savedFile)); } catch (Exception e) { e.printStackTrace(); } String path = savedFile.getPath(); // 将文件的信息封装在对象中 FileInfo file = new FileInfo(); if (userAll != null) { file.setUploadPersonId(userAll.getUser().getUserId()); } else { mav.setViewName("login"); return mav; } file.setFileName(st[0]); file.setFilePath(path); Date date = new Date(); file.setUploadDate(date); file.setFileSize(fileSize); file.setFileType(fileType); file.setFileForm(st[1]); if ("superman".equals(userAll.getUser().getUserNumber())) { file.setFileShare("Y"); file.setCheckFlag("Y"); } else { file.setFileShare(share); file.setCheckFlag("N"); } file.setDeleteFlag("N"); file.setDownloadTimes(0); // 保存文件的信息 boolean bool = fileSer.saveFile(file); String userNumber = userAll.getUser().getUserNumber(); //设置跳转界面 mav.setViewName("jsp/person/upload"); logSer.saveLog("用户\"" + userNumber + "\"上传文件\"" + file.getFileName() + "\""); mav.getModel().put("bool", bool); return mav; } /** * Purpose:下载文档 * * @param fileId 文件id * @return */ @RequestMapping("download") public void download(Integer fileId, HttpServletResponse resp) { FileInfo file = new FileInfo(); //通过文件id获取文件的基本信息 file = fileSer.getFileById(fileId); // 根据文件后缀名设置文件的mime类型 String mime = "application/"; switch (file.getFileForm()) { case "doc": mime = mime + "msword"; break; case "docx": mime = mime + "msword"; break; case "pdf": mime = mime + "pdf"; break; case "xls": mime = mime + "vnd.ms-excel"; case "ppt": mime = mime + "vnd.ms-powerpoint"; break; case "txt": mime = "text/plain"; break; default: break; } resp.setContentType(mime); String fileName = file.getFileName(); String name = ""; try { // 将文件名使用utf-8编码格式编码,使其中的中文字符可以正常显示 name = URLEncoder.encode(fileName, "utf-8"); } catch (UnsupportedEncodingException e1) { e1.printStackTrace(); } // 弹框选择保存路径 resp.setHeader("content-disposition", "attachment;filename=" + name + "." + file.getFileForm() + ";filename*=utf-8''" + name + "." + file.getFileForm()); String filePath = file.getFilePath(); InputStream is = null; OutputStream os = null; try { is = new BufferedInputStream(new FileInputStream(filePath)); os = new BufferedOutputStream(resp.getOutputStream()); byte[] buff = new byte[1024]; @SuppressWarnings("unused") int count; while ((count = is.read(buff)) != -1) { os.write(buff); } //修改下载次数 fileSer.update(fileId); } catch (Exception e) { e.printStackTrace(); } finally { //最后,要记得关闭输入流和输出流 if (is != null) { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } if (os != null) { try { os.close(); } catch (IOException e) { e.printStackTrace(); } } } }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。
赞 (0)