"Java" Picture upload __java

Source: Internet
Author: User

Image upload function in the controller layer to achieve the complete method is as follows:

Method One:

@RequestMapping ("touploadimage.do") public String upload (@RequestParam multipartfile uploadfile,  HttpServletRequest request, HttpServletResponse response,string tid) {//Get the filename you entered String filename  
           = Uploadfile.getoriginalfilename ();  
           if (Stringutils.isempty (FileName)) {System.out.println ("not uploaded file name is empty");  
                   //Get path String TempPath = Request.getsession (). Getservletcontext (). Getrealpath ("/")  
           + "Upload\\ysdwanimal";           
           File dir = new file (TempPath);  
           if (!temppath.endswith (File.separator)) {TempPath = TempPath + file.separator;  
           } if (!dir.exists ()) {dir.mkdirs ();  
           } System.out.println (Temppath+filename);  
           Check if repeat upload hmimages hmimage = Hmimageservice.getentrybyid (TID);  
    if (hmimage = = null) {        return "Uploadfail";  
                //Rewrite Database store path String lj=request.getscheme () + "://" + Request.getservername ()  
           + ":" + request.getserverport () + "/whzhly/upload/ysdwanimal/" +id+ ". jpg";  
           Save Path Ysdwanimal.setlujing (LJ);  
           Ysdwanimalservice.saveorupdateysdwanimal (Ysdwanimal);           
           Gets the complete picture name String NewFile = TempPath + id+ ". jpg";  
           File File = new file (newFile);  
                 
               The picture is copied to the specified folder, implementing the path try {filecopyutils.copy (uploadfile.getbytes (), file);  
           System.out.println ("successful upload");  
               catch (IOException e) {e.printstacktrace ();  
           return "Uploadfail";  
       Return to "uploadsuccess";   }


Method Two:

@RequestMapping ("/touploadhmimage.do") public @ResponseBody String Touploadhmimage (httpservletrequest request,
		HttpServletResponse Response,modelmap model) {//Get to project name String projectname = Request.getcontextpath (); Get uploaded files to save the directory, will upload the file stored in the Web-inf directory, do not allow direct access to the outside, to ensure that the upload file security String Savepath = Request.getservletcontext (). Getrealpath ("/
		Web-inf/primary/images ");
		File File = new file (Savepath);
		To determine if the saved directory of the uploaded file exists if (!file.exists () &&!file.isdirectory ()) {//does not exist, create the directory File.mkdir ();
		}//message prompts String messages = "";
			try {diskfileitemfactory factory = new Diskfileitemfactory ();
			Create a file upload parser servletfileupload upload = new Servletfileupload (factory);
			Upload.setheaderencoding ("Utf-8");
			The total size of the uploaded file cannot exceed 5M Upload.setsizemax (1024 * 1024 * 5); Determine if the data submitted is the data of the upload form if (!
			Servletfileupload.ismultipartcontent (Request)) {return message; * * * Using the Servletfileupload parser to parse the upload data, * The result returned is a list<fileitem> set * * * list<fileitem> list = upload.parserequest (request); for (Fileitem item:list) {if (Item.isformfield ()) {//If Fileitem encapsulates data String itemname = Item.getfieldname () for ordinary entries
					;
					String Itemvalue = item.getstring ("Utf-8");
				System.out.println (itemname + "=" + Itemvalue); 
					}else {//If Fileitem is encapsulated upload file//Get uploaded file name String fileName =item.getname ();
					System.out.println ("filename=" + fileName);
					if (FileName = = NULL | | Filename.trim (). Equals ("")) {continue;
					//Process The path portion of the filename of the uploaded file that is retrieved, leaving only the filename part filename = filename.substring (filename.lastindexof ("\") +1);
					Gets the input stream of the uploaded file in item InputStream InputStream = Item.getinputstream ();
					Create a file output stream FileOutputStream OutputStream = new FileOutputStream (savepath+ "\" +filename);
					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 while (Len=inputstream.read (buffer) >0) {//using FILEOUTPU TstrThe EAM output stream writes the data of the buffer to the specified directory (Savepath + "\" + filename) outputstream.write (buffer, 0, Len);
					//Close the input stream inputstream.close ();
					Turn off the output stream outputstream.close ();
					Deletes the temporary files generated when processing file uploads item.delete ();
				message = "File upload succeeded"; The file upload failed with the catch (Exception e) {message=}}.
			 ";
		E.printstacktrace ();
		
	} return message; }




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.