Two kinds of Java file upload instance explain _java

Source: Internet
Author: User

This article through two kinds of file upload instances to compare, to help you better learn the Java file Upload function, the specific contents are as follows

1. Java Attachment Upload Code

@Controller public class UploadFile extends basejsoncontroller{/** * Attachment upload * * @param request * @param c Reativefile * @param response * @return/@RequestMapping (value = "/upload/uploadfile.json") public void UPL Oadfile (httpservletrequest request,httpservletresponse response) {/** * 1, in order to ensure server security, upload files should be placed in the outside directory can not directly access, such as in the web-
     INF directory.
     * 2, in order to prevent the occurrence of file coverage, to upload files to produce a unique file name.
     * 3, to prevent a directory to appear too many files, to use the hash algorithm to break storage.
     * 4, to limit the maximum upload file value.
     * 5, to limit the type of upload file, when you receive the upload file name, determine whether the suffix name is legitimate. * *//Get uploaded file to save the directory, will upload the file stored in the Web-inf directory, do not allow the outside direct access to ensure that the upload file security String Savepath = Request.getsession (). Getservletcontex
    T (). Getrealpath ("/web-inf/upload");
    Temporary files generated on upload save directory String TempPath = Request.getsession (). Getservletcontext (). Getrealpath ("/web-inf/temp");
    File Tmpfile = new file (TempPath);
    if (!tmpfile.exists ()) {//Create temporary directory Tmpfile.mkdirs ();
    }//message prompts Jsonarray arr = new Jsonarray ();
  Map<string,object> map = null;   
    InputStream in = null;
    FileOutputStream out = null; try{///Use Apache File Upload component to process file upload steps://1, create a diskfileitemfactory factory diskfileitemfactory factory = new Diskfilei
      Temfactory ();
      Sets the size of the factory's buffer, and when the uploaded file size exceeds the buffer size, a temporary file is generated to be stored in the specified temporary directory. Factory.setsizethreshold (1024*100)//Set buffer size of 100KB, if unspecified, then the buffer size defaults to 10KB//Set the Save directory for temporary files generated when uploading Factory.setrepos
      Itory (tmpfile);
      2, create a file upload parser servletfileupload upload = new Servletfileupload (factory); Monitor File Upload Progress Upload.setprogresslistener (new Progresslistener () {public void update (long pbytesread, long Pcont
        entlength, int arg2) {System.out.println ("File size: + Pcontentlength +", currently processed: "+ pbytesread);"
      }
      }); 
      Solve the upload file name of Chinese garbled upload.setheaderencoding ("UTF-8"); 3, to determine whether the data submitted is uploaded form data if (!
      Servletfileupload.ismultipartcontent (Request)) {//Get data return in the traditional way;
  //Set the maximum size of a single file to upload, which is currently set to 1024*1024 Byte, which is 20MB    Upload.setfilesizemax (1024*1024*20);
      Set the maximum number of uploaded files, maximum = The maximum size of multiple files uploaded at the same time, currently set to 40MB Upload.setsizemax (1024*1024*40); 4, using the Servletfileupload parser to parse the upload data, the result returned is a list<fileitem> collection, each fileitem corresponding to a form of the entry @SuppressWarnings ("
 
      Unchecked ") list<fileitem> List = upload.parserequest (request); for (Fileitem item:list) {//If the data in Fileitem is encapsulated by the normal input item if (Item.isformfield ()) {String name = Item.
          GetFieldName ();
          Solve the Chinese garbled problem of the data of the normal input item String value = item.getstring ("UTF-8");
          Value = new String (value.getbytes ("iso8859-1"), "UTF-8");
        SYSTEM.OUT.PRINTLN (name + "=" + value);
          }else{//If the Fileitem is encapsulated in the upload file//Get uploaded file name, String filename = Item.getname ();
          if (Filename==null | | Filename.trim (). Equals ("")) {continue; //Note: Different browsers submit the file name is not the same, some browsers submit the file name is a path, such as: C:\a\b\1.txt, and some just simple file name, such as: 1.txt//processing acquired upload file filename of the path section , just keep the textPart filename = filename.substring (filename.lastindexof ("\") +1); Get upload file extension String fileextname = filename.substring (Filename.lastindexof (".")
          +1); If you need to limit the type of files you upload, you can use the file's extension to determine whether the file type you are uploading is legitimate if (Stringutils.equals (Fileextname, "rar") | | Stringutils.equals (fileextname, "zip")) {throw new Bizexception ("", "Prohibit uploading of compressed files!)
          ");
          /*************///Get input stream in = Item.getinputstream () of the uploaded file in item;
          /************///Get File Save name String savefilename = makefilename (filename);
          Get 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];
          Determine if the data in the input stream has been read out of the identity int len = 0; The loop reads the input stream into the buffer, (len=in.read (buffer)) >0 indicates that there is also data in inside while (len=in.reAD (buffer)) {//>0 the buffer data using the FileOutputStream output stream to the specified directory (Savepath + "\" + filename) out.write (
          Buffer, 0, Len);
          //Close the input stream in.close ();       
          Turn off the output stream out.close ();       
          Deletes the temporary files generated when processing file uploads item.delete ();
          Map = new hashmap<string,object> ();
          Map.put ("Savefilename", savefilename);
          Map.put ("Realsavepath", Realsavepath);
        Arr.add (map); 
    } returnsuccessjson ("Upload succeeded", arr, response);
      }catch (fileuploadbase.filesizelimitexceededexception e) {e.printstacktrace (); Returnfailjson (E.getmessage (), "Single file exceeds 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 ();
      Turn off the output stream out.close (); catch (IOException e) {}}}/** * @Method: Makefilename * @Description: Generate file name for upload file, filename  To: Uuid+ "_" + the original name of the file * @Anthor: Xuwentao * @param the original name of the filename * @return uuid+ "_" + the original name of the file * * * Private String Makefilename (String filename) {//2.jpg//To prevent file overwrite, to generate a unique file name for the upload file return Uuid.randomuuid (). toString () + "_"
  + filename; /** * To prevent too many files from appearing under a directory, use the hash algorithm to break up storage * @Method: Makepath * @Description: * @Anthor: Xuwentao * * @p Aram filename filename, to generate storage directory based on filename * @param savepath file storage path * @return New storage directory/private string Makepath (string file
    Name,string Savepath) {//Get the filename of the hashcode value, get the filename of this string object in memory address int hashcode = Filename.hashcode (); int dir1 = hashcode&0xf; 0--15 int dir2 = (hashcode&0xf0) >>4; 0-15//Construct new save directory String dir = savepath + "\" + Dir1 + "\\ "+ Dir2;
    Upload\2\3 upload\3\5//file can represent either a file or a directory file = new file (dir);
    If the directory does not exist if (!file.exists ()) {///Create directory File.mkdirs ();
  } return dir;
 }
}

2. Java Upload resume Code

/** * Upload Resume * 1--Create file failed 2--exception 3--upload failed 4--file did not get 5--file not deleted 6--please upload Word, Excel, ppt, PDF file */* Path separator: For adaptive operating system/private S
 
 Tatic final String file_separator = System.getproperties (). GetProperty ("File.separator");
 /** * Upload file * * @param FileIO * @param oldcontracturl * @param request * @return return address (relative address, non-absolute address) * * * @Override Public String upload (multipartfile FileIO, String oldcontracturl, HttpServletRequest request) {String Uploadurl = re
   Quest.getsession (). Getservletcontext (). Getrealpath ("files"); Delete files and folders if (Oldcontracturl!= null) {String olddirectory = oldcontracturl.substring (5, OLDCONTRACTURL.L
     Astindexof (File_separator));
     File File = new file (Uploadurl + olddirectory);
     Boolean flag = Deletedir (file);
       if (!flag) {logger.error ("Old file deletion failed");
     Return "5";
   }//Upload a new CV file long now = System.currenttimemillis ();
   Uploadurl = Uploadurl + file_separator + now + file_separator;
  String resumename = ""; if (!
     Fileio.isempty ()) {ResumeName = Stringutils.deletewhitespace (Fileio.getoriginalfilename ()); To determine the file suffix/*string suffix = resumename.substring (Resumename.lastindexof ("."), Resumename.length ()). toLowerCase
     (); if (! ". Doc ". Equals (suffix) &&!". Docx ". Equals (suffix) &&!". XLS ". Equals (suffix) &&!". Xlsx ". Equals (suffix) &&!". ppt ". Equals (suffix) &&!". Pptx ". Equals (suffix) &&!".
       PDF ". Equals (suffix)) {logger.error (" Not Word, Excel, ppt, pdf file ");
     return "6";
     }*/} else {logger.error ("File not fetched");
   Return "4";
   File dir = new file (Uploadurl);
   if (!dir.exists ()) {dir.mkdirs ();
   The 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 ("statement exception", e);
   Return "2";
     catch (IOException e) {logger.error ("Upload failed", e);
   Return "3";
 Return to File_separator + "files" + File_separator + now + file_separator + resumename; /** * Recursively deletes all files and subdirectories under the directory * @param dir * @return boolean Returns "true" if all were SUCCESSF of the file directory to be deleted
 Ul.
 * 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 deletes subdirectories in the directory for (int i = 0; i < children.length; i++) {Boolean success = Deletedir (New File (dir, Childr
       En[i]));
       if (!success) {return false;
 }}//directory is empty at this time, you can delete return Dir.delete ();
 }

The above is the entire content of this article, I hope to help you learn, master Java file upload skills.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.