This article compares two file upload examples to help everyone better learn the Java file upload function. The specific content is as follows
1. Java attachment upload code
@Controllerpublic class UploadFile extends BaseJsonController{ /** * Attachment upload* * @param request * @param creativeFile * @param response * @return */ @RequestMapping(value = "/upload/uploadFile.json") public void uploadFile(HttpServletRequest request,HttpServletResponse response) { /** * 1. To ensure the security of the server, the uploaded file should be placed in a directory that cannot be directly accessed by the outside world, such as in the WEB-INF directory. * 2. To prevent file overwriting, a unique file name must be generated for uploading the file. * 3. To prevent too many files from appearing under a directory, you must use the hash algorithm to break up the storage. * 4. The maximum value of uploaded files should be limited. * 5. To limit the type of uploaded files, when receiving the uploaded file name, determine whether the suffix name is legal. */ //Get the uploaded file save directory, store the uploaded file in the WEB-INF directory, and does not allow direct access from the outside world to ensure the security of uploaded files String savePath = request.getSession().getServletContext().getRealPath("/WEB-INF/upload"); //The temporary file saving directory generated during upload String tempPath = request.getSession().getServletContext().getRealPath("/WEB-INF/temp"); File tmpFile = new File(tempPath); if (!tmpFile.exists()) { //Create a temporary directory tmpFile.mkdirs(); } //The message prompts JSONArray arr = new JSONArray(); Map<String,Object> map = null; InputStream in = null; FileOutputStream out = null; try{ //Use the Apache file upload component to handle file upload steps: //1. Create a DiskFileItemFactory factory DiskFileItemFactory factory = new DiskFileItemFactory(); //Set the size of the factory's buffer. When the uploaded file size exceeds the size of the buffer, a temporary file will be generated and stored in the specified temporary directory. factory.setSizeThreshold(1024*100);//Set the buffer size to 100KB. If not specified, the buffer size is 10KB by default. //Set the storage directory of the temporary file generated during uploading factory.setRepository(tmpFile); //2. Create a file upload parser ServletFileUpload upload = new ServletFileUpload(factory); //Supert the file upload progress upload.setProgressListener(new ProgressListener(){ public void update(long pBytesRead, long pContentLength, int arg2) { System.out.println("File size is: " + pContentLength + ", currently processed: " + pBytesRead); } }); //Solve the Chinese garbled upload.setHeaderEncoding("UTF-8"); //3. Determine whether the submitted data is the data of the upload form if(!ServletFileUpload.isMultipartContent(request)){ //Get data return according to the traditional way; } //Set the maximum size of the uploaded single file, which is currently set to 1024*1024 bytes, that is, 20MB upload.setFileSizeMax(1024*1024*20); //Set the maximum value of the total number of uploaded files. The maximum value = the sum of the maximum sizes of multiple files uploaded at the same time. It is currently set to 40MB upload.setSizeMax(1024*1024*40); //4. Use the ServletFileUpload parser to parse the uploaded data. The parsing result returns a List<FileItem> collection. Each FileItem corresponds to the input item of a Form form @SuppressWarnings("unchecked") List<FileItem> list = upload.parseRequest(request); for(FileItem item : list){ //If the data of ordinary input items are encapsulated in the fileitem if(item.isFormField()){ String name = item.getFieldName(); //Solve the Chinese garbled problem of data of ordinary input items String value = item.getString("UTF-8"); //value = new String(value.getBytes("iso8859-1"),"UTF-8"); System.out.println(name + "=" + value); }else{//If the file item is encapsulated in the uploaded file//Get the uploaded file name, String filename = item.getName(); if(filename==null || filename.trim().equals("")){ continue; } //Note: The file names submitted by different browsers are different. Some browsers submit file names with paths, such as: c:/a/b/1.txt, while some are just simple file names, such as: 1.txt // Process the path part of the file name of the obtained uploaded file, only the file name part is retained filename = filename.substring(filename.lastIndexOf("//")+1); //Get the extension of the uploaded file String fileExtName = filename.substring(filename.lastIndexOf(".")+1); //If you need to limit the uploaded file type, you can use the file extension to determine whether the uploaded file type is legal if(StringUtils.equals(fileExtName, "rar") || StringUtils.equals(fileExtName, "zip")){ throw new BizException("","Upload compressed files is prohibited! "); } /***************/ //Get the input stream of the uploaded file in the item = item.getInputStream(); /******************/ //Get the name of the file saved String saveFilename = makeFileName(filename); //Get the file save directory String realSavePath = makePath(saveFilename, savePath); //Create a file output stream out = new FileOutputStream(realSavePath + "//" + saveFilename); //Create a buffer byte buffer[] = new byte[1024]; //The identification of whether the data in the input stream has been read is int len = 0; //The loop reads the input stream into the buffer, (len=in.read(buffer))>0 means that there is still data in in while((len=in.read(buffer))>0){ //Use FileOutputStream output stream to write the buffer data to the specified directory (savePath + "//" + filename) out.write(buffer, 0, len); } //Close the input stream in.close(); //Close the output stream out.close(); //Delete the temporary file generated when processing file upload item.delete(); map = new HashMap<String,Object>(); map.put("saveFilename", saveFilename); map.put("realSavePath", realSavePath); arr.add(map); } } returnSuccessJSON("UploadBase.FileSizeLimitExceededException e) { e.printStackTrace(); returnFailJSON(e.getMessage(), "Single file exceeds the maximum value!!!", response); }catch (FileUploadBase.SizeLimitExceededException e) { e.printStackTrace(); returnFailJSON(e.getMessage(), "The total size of the uploaded file exceeds the maximum limit! ! ! ", response); arr.toString(); }catch (Exception e) { e.printStackTrace(); returnFailJSON(e.getMessage(), "File upload failed!", response); arr.toString(); } finally{ try { //Close the input stream in.close(); //Close the output stream out.close(); } catch (IOException e) { } } } /** * @Method: makeFileName * @Description: Generate the file name of the uploaded file, with the file name as: uuid+"_"+ the original name of the file* @Anthor:xuwentao * @param filename Original name of the file * @return uuid+"_"+The original name of the file */ private String makeFileName(String filename){ //2.jpg //To prevent file overwriting, a unique file name must be generated for uploading the file return UUID.randomUUID().toString() + "_" + filename; } /** * To prevent too many files from appearing in a directory, you need to use the hash algorithm to break up the storage* @Method: makePath * @Description: * @Anthor:xuwentao * * @param filename File name, generate storage directory based on the file name* @param savePath File storage path* @return New storage directory */ private String makePath(String filename,String savePath){ //Get the hashCode value of the file name, and what you get is the address of the string object filename in memory int hashcode = filename.hashCode(); int dir1 = hashcode&0xf; //0--15 int dir2 = (hashcode&0xf0)>>4; //0-15 //Construct a new save directory String dir = savePath + "//" + dir1 + "//" + dir2; //upload/2/3 upload/3/5 //File can represent both files and directories File file = new File(dir); //If the directory does not exist if(!file.exists()){ //Create the directory file.mkdirs(); } return dir; }}2. Java upload resume code
/** * Upload resume* 1-File creation failed 2-Exception 3-Upload failed 4-File not obtained 5-File not deleted 6-Please upload word, excel, ppt, pdf files*/ /*Path separator: used in adaptive operating system*/ private static final String FILE_SEPARATOR = System.getProperties() .getProperty("file.separator"); /** * Upload file* * @param FileIO * @param oldContractURL * @param request * @return Return file address (relative address, non-absolute address) */ @Override public String upload(MultipartFile FileIO, String oldContractURL, HttpServletRequest request) { String uploadUrl = request.getSession().getServletContext().getRealPath("files"); //Delete files and folders if (oldContractURL != null) { String oldDirectory = oldContractURL.substring(5, oldContractURL.lastIndexOf(FILE_SEPARATOR)); File file = new File(uploadUrl + oldDirectory); boolean flag = deleteDir(file); if (!flag) { logger.error("Old file deletion failed"); return "5"; } } //Upload new resume file long now = System.currentTimeMillis(); uploadUrl = uploadUrl + FILE_SEPARATOR + now + FILE_SEPARATOR; String resumeName = ""; if (!FileIO.isEmpty()) { resumeName = StringUtils.deleteWhitespace(FileIO.getOriginalFilename()); //Judge file suffix/*String suffix = resumeName.substring(resumeName.lastIndexOf("."), resumeName.length()) .toLowerCase(); if (!".doc".equals(suffix) && !".docx".equals(suffix) && !".xlsx".equals(suffix) && !".xlsx".equals(suffix) && !".ppt".equals(suffix) && !",.pptx",.equals(suffix) && !",.pdf",.equals(suffix)) { logger.error("not word, excel, ppt, pdf files"); return "6"; }*/ } else { logger.error("File not obtained"); return "4"; } File dir = new File(uploadUrl); if (!dir.exists()) { dir.mkdirs(); } File targetFile = new File(uploadUrl + resumeName); if (!targetFile.exists()) { try { targetFile.createNewFile(); } catch (IOException e) { logger.error("File creation failed", e); return "1"; } } try { FileIO.transferTo(targetFile); } catch (IllegalStateException e) { logger.error("Sentence exception", e); return "2"; } catch (IOException e) { logger.error("Upload failed", e); return "3"; } return FILE_SEPARATOR + "files" + FILE_SEPARATOR + now + FILE_SEPARATOR + resumeName; } /** * Recursively delete all files in the directory and all files in the subdirectories* @param dir The file directory to be deleted* @return boolean Returns "true" if all deletions were successful. * If a deletion fails, the method stops attempting to * delete and returns "false". */ public boolean deleteDir(File dir) { if (dir.isDirectory()) { String[] children = dir.list(); //Recursively delete the subdirectories in the directory for (int i = 0; i < children.length; i++) { boolean success = deleteDir(new File(dir, children[i])); if (!success) { return false; } } } // The directory is empty at this time, you can delete return dir.delete(); }The above is all the content of this article. I hope it will be helpful to everyone's learning and master the skills of uploading Java files.