SPRINGMVC frame--Common interface image upload interface

Source: Internet
Author: User

I want the image upload interface refers to the server side after the completion of the image upload, return an accessible image address .

The Spring MVC Framework film upload is very simple, as follows

1@RequestMapping (value= "/uploadimg", method=requestmethod.post)2 @ResponseBody3  PublicString uploadimg (@RequestParam (value= "img") multipartfile img) {4File f =NewFile ("/data/images");5     Try{6 Fileutils.copyinputstreamtofile (Img.getinputstream (), f);7}Catch(Exception e) {8 e.printstacktrace ();9     }Ten     return"Upload succeeded"; One}

It's very simple!

1 <formAction= "HTTP://LOCALHOST/COMPONENT/COMMON/UPLOADIMG"Method= "POST"enctype= "Multipart/form-data">2Avatar:<inputtype= "File"name= "img" /><BR/>3     <inputtype= "image"src= "./images/img_submit.gif" />4 </form>

The above is only able to upload files, and we will be able to return a picture address, the image address to be able to directly access in the browser, as follows:

Direct Code It!

Controller layer

1@RequestMapping (value= "/uploadimg", method=requestmethod.post)2 @ResponseBody3  PublicString uploadimg (@RequestParam (value= "img") multipartfile img, httpservletresponse response) {4Jsonobject result =NewJsonobject ();5     BooleanFlag =true;6     Try {7Flag =pictureuploadservice.upload (img, result);8}Catch(Exception e) {9Result.put ("mess", "Call failed");TenFlag =false; One e.printstacktrace (); A     } -Result.put ("Flag", flag); -      theResponse.setcontenttype ("Text/html;charset=utf-8"); -     //troubleshoot cross-domain access issues -Response.setheader ("Access-control-allow-origin", "*"); -      +     returnresult.tostring (); -}
View Code

Service Layer

1 /**2 * Upload Images3  * @paramfile4  * @paramparams5  * @return6  * @throwsException7  */8  Public BooleanUpload (multipartfile file, jsonobject params)throwsexception{9     //Filter the legal file typesTenString FileName =file.getoriginalfilename (); OneString suffix = filename.substring (Filename.lastindexof (".") +1); AString Allowsuffixs = "Gif,jpg,jpeg,bmp,png,ico"; -     if(allowsuffixs.indexof (suffix) = =-1){ -Params.put ("ResultStr", "not support the file type!"); the         return false; -     } -      -     //Get network address, local address header +Properties config =NewProperties (); -Config.load ( This. GetClass (). getClassLoader (). getResourceAsStream ("Config.properties")); +String URLPath = Config.getproperty ("UrlRoot"); AString LocalPath = Config.getproperty ("Localroot"); at      -     //Create a new directory -String uri = File.separator +dateutil.getnowdatestr (file.separator); -File dir =NewFile (LocalPath +URI); -     if(!dir.exists ()) { - dir.mkdirs (); in     } -      to     //Create a new file +String NewFileName =stringutil.getuniquefilename (); -File f =NewFile (Dir.getpath () + file.separator + NewFileName + "." +suffix); the      *     //copy data from the input stream to a new file $ Fileutils.copyinputstreamtofile (File.getinputstream (), f);Panax Notoginseng      -     //Create a Picture object thePicture pic =NewPicture (); + Pic.setlocalpath (F.getabsolutepath ()); A Pic.setname (F.getname ()); thePic.seturl (URLPath + uri.replace ("\ \", "/") + "/" + NewFileName + "." +suffix); +Pic.setaddtime (NewDate ()); -      $     //inserting into a database $     //... -      -Params.put ("ResultStr", Pic.geturl ()); the      -     return true;Wuyi}
View Code

(There is no DAO layer, I configure the domain name of the network address in the properties and the local file storage directory)

There are several places to note to upload files:

  • Upload files in Chinese garbled (this is not considered, after all, to achieve is the image upload)
  • Limit the size of the upload file (the file is too large to cause the server to be overwhelmed), which we limit in spring MVC configuration file
    1 <Beans:beanID= "Multipartresolver"class= "Org.springframework.web.multipart.commons.CommonsMultipartResolver">2     <Beans:propertyname= "Defaultencoding"value= "Utf-8" />3     <Beans:propertyname= "Maxuploadsize"value= "10485760000" />4     <Beans:propertyname= "Maxinmemorysize"value= "40960" />5 </Beans:bean>
  • Limit upload file types (this we process at the service layer)
  • If more than 1000 files are saved under a folder, the file access performance will be affected, so the uploaded files should be distributed in a variety of ways, without having to stick to one. I'm slacking off here.Month DayAsDirectory Hierarchy
    1 /**2 * Get the current date string3  * @paramSeparator4  * @return5  */6  Public Staticstring Getnowdatestr (String separator) {7Calendar now =calendar.getinstance ();8     intYear =Now.get (calendar.year);9     intmonth = Now.get (calendar.month) +1;Ten     intDay =Now.get (calendar.date); One      A     returnYear + separator + month + separator +Day ; -}
  • Files saved after successful upload cannot have duplicate names (that is, the file name is unique)
    1 // generate a unique file name 2  Public Static String GetUniqueFileName () {3     String str = uuid.randomuuid (). toString (); 4     return str.replace ("-", "" "); 5 }

The upload image process is as follows:

After clicking Upload, return

Enter the above image address in the browser to access it and then appear

SPRINGMVC frame--Common interface image upload interface

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.