java web upload files and download file snippets to share

  • 2020-06-01 09:49:13
  • OfStack

The example of this article is to share the specific code of java web to upload files and download files for your reference, the specific content is as follows


 /**
  * Purpose : upload documents 
  * 
  * @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();
  //  Gets the size of the file 
  String fileSize = "";
  int length = req.getContentLength();
  // Converted to KB
  double len1 = (double) (Math.round((length / 1024) * 100)) / 100;
  // Converted to MB
  double len2 = (double) (Math.round((len1 / 1024) * 100)) / 100;
  if (len2 > 1) {
   fileSize = String.valueOf(len2) + "MB";
  } else {
   fileSize = String.valueOf(len1) + "KB";
  }
  // Converts the request into a request to process the file 
  MultipartRequest mreq = (MultipartRequest) req;
  // File upload special class 
  MultipartFile mfile = mreq.getFile("uploadFile");

  //  Get the context path 
  String root = req.getSession().getServletContext().getRealPath("/");
  File dir = new File(root);
  //  Gets the filename and file mime type 
  String str = mfile.getOriginalFilename();
  String[] st = str.split("\\.");

  File savedFile = null;
  try {
   // Creates in the specified directory 1 Two new empty files prefixed with the name of the file "upload_"
   savedFile = File.createTempFile("upload_", mfile.getOriginalFilename(), dir);
   // Copies the contents of the buffer to the newly created file 
   FileCopyUtils.copy(mfile.getInputStream(), new FileOutputStream(savedFile));
  } catch (Exception e) {
   e.printStackTrace();
  }
  String path = savedFile.getPath();

  //  Encapsulates information about a file in an object 
  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);
  //  Save the file information 
  boolean bool = fileSer.saveFile(file);
  String userNumber = userAll.getUser().getUserNumber();
  // Set jump interface 
  mav.setViewName("jsp/person/upload");
  logSer.saveLog(" The user \"" + userNumber + "\" Upload a file \"" + file.getFileName() + "\"");
  mav.getModel().put("bool", bool);
  return mav;
 }

 /**
  * Purpose : download the document 
  * 
  * @param fileId  file id
  * @return
  */
 @RequestMapping("download")
 public void download(Integer fileId, HttpServletResponse resp) {
  FileInfo file = new FileInfo();
  // Through the file id Get basic information about the file 
  file = fileSer.getFileById(fileId);

  //  Set the file by its suffix name mime type 
  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 {
   //  Use the filename utf-8 Encoding format encoding, so that the Chinese characters can be displayed normally 
   name = URLEncoder.encode(fileName, "utf-8");
  } catch (UnsupportedEncodingException e1) {
   e1.printStackTrace();
  }

  //  Select save path 
  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);
   }
   // Modify download times 
   fileSer.update(fileId);
  } catch (Exception e) {
   e.printStackTrace();
  } finally {
   // Finally, remember to close the input and output streams 
   if (is != null) {
    try {
     is.close();
    } catch (IOException e) {
     e.printStackTrace();
    }
   }
   if (os != null) {
    try {
     os.close();
    } catch (IOException e) {
     e.printStackTrace();
    }
   }
  }
 }

Related articles: