Uploading image files using spring MVC

Source: Internet
Author: User

This article turns from: http://amcucn.iteye.com/blog/264457. Thanks to the author

Recently in the work, need to use to upload images of the function, but they usually learn only use struts upload function, but because the project did not use struts, but spring MVC, and finally had to find another way. Through Google and Baidu, see a number of relevant introduction. After their own trial, finally take advantage of the spring MVC upload files to complete the image upload. If you just want to upload a picture, you can do so by restricting the extension to the name. The following is a key part of the code.

About the configuration of spring I'm not here to introduce you, the following method is based on the spring MVC pattern.

Front desk section:

Actually the foreground part is very simple, is the common form form file upload form to be possible. Such as:

HTML code
    1.  <form  action= "comm_addproduct.do?method=saveproduct"  < span class= "attribute" >method= "post"  enctype= "Multipart/form-data" >  
    2.   <input  name= "imgfile"  id=< Span class= "Attribute-value" > "imgfile"  type= "file"  />  
    3. </form>  

The key point here is that the enctype= "Multipart/form-data" attribute must be in the form form. As for why this attribute is needed, I think it is clear to those who have done the file upload. I'm not going to say much. Do not search for a bit! The front desk here is very simple, just a demo.

After the current form is submitted to the background, we focus on how the background handles the uploaded files. The key code is as follows:

Java code
  1. /**
  2. * Upload the image file and save it to the specified path
  3. */
  4. public void AddImage (httpservletrequest request,string path1,string path2) {
  5. //transition to Multiparthttprequest (where the focus is)
  6. Multiparthttpservletrequest multipartrequest = (multiparthttpservletrequest) request;
  7. //Get the 1th picture (file uploaded according to the name of the foreground)
  8. Multipartfile imgFile1 = Multipartrequest.getfile ("Imgfile");
  9. //Define an array to hold the file types that can be uploaded
  10. List filetypes = new ArrayList ();
  11. Filetypes.add ("JPG");
  12. Filetypes.add ("JPEG");
  13. Filetypes.add ("BMP");
  14. Filetypes.add ("gif");
  15. //Save first picture
  16. if (! ( Imgfile1.getoriginalfilename () = =Null | | " . Equals (Imgfile1.getoriginalfilename ()))) {  
  17. /* The method that is called below is primarily used to detect if the uploaded file is within the allowed type range, and according to the path name passed in
  18. * Automatically create folders and file names, return file files we can use to do other uses, such as to get the file name path after saving
  19. * I'm not going to do a long introduction here.
  20. */
  21. File file1 = this.getfile (imgFile1, filetypes,path1,path2);
  22. }
  23. }
  24. <p>
  25. </p><p> in fact, the above code is relatively simple, the focus is to convert our common request object to <span style="WHITE-SPACE:PRE;" >multiparthttprequest object, with this object, we can get the user uploaded files. Get the user uploaded files after,</span></p>
  26. <p><span style="WHITE-SPACE:PRE;" > We can do something we want to do. In the above we have also done some things, that is to determine whether the user upload file type is our definition of the </span></p>
  27. <p> the type within the array, as to how to determine if it is a type that is allowed to upload, I will give it in the following method. In fact, the following code can be written in a method, but for reuse, I have written separately. Perhaps my approach is not the best. That's the equivalent of giving everyone a direction! </p>
  28. <p> </p>
  29. <p> Let's take a look at the following two methods, which are two of the most important things to do. First, to determine whether the user uploaded files are within the scope of our defined types, and second, save the file to the specified path, this path is created by ourselves. </p>
  30. <p>
  31. </p><pre name="code" class="java" >/**
  32. * Read the file through the incoming page, save to the local disk after processing, and return an already created file
  33. * @param imgfile files read from the page
  34. * @param the category name of the TypeName product
  35. * @param brand name of brandname product
  36. * @param filetypes allowed file name extensions collection
  37. * @return
  38. */
  39. private File getFile (multipartfile imgfile,string typename,string brandname,list filetypes) {
  40. String fileName = Imgfile.getoriginalfilename ();
  41. //Get the extension of the upload file type, first get the location, then intercept from the next position of the. To the end of the file, and finally get the extension
  42. String ext = filename.substring (Filename.lastindexof (".")  +1,filename.length ());
  43. //Lowercase conversions for extensions
  44. ext = Ext.tolowercase ();
  45. File file = null;
  46. If (filetypes.contains (EXT)) { //If the extension belongs to a type that is allowed to be uploaded, the file is created
  47. File = This.creatfolder (typeName, brandname, fileName);
  48. try {
  49. Imgfile.transferto (file); //Save the uploaded file
  50. } catch (IllegalStateException e) {
  51. E.printstacktrace ();
  52. } catch (IOException e) {
  53. E.printstacktrace ();
  54. }
  55. }
  56. return file;
  57. }
  58. /** 
  59. * Detect and create a level, Level two folder, file name
  60. Here I am using the two strings passed in to do the first level folder and the level two folder name
  61. In this way we can do it according to the user's choice to save to the appropriate folder
  62. */
  63. private File Creatfolder (String typename,string brandname,string fileName) {
  64. File file = null;
  65. TypeName = Typename.replaceall ("/", "" "); //Remove "/"
  66. TypeName = Typename.replaceall ("", ""); //Replace half-width spaces
  67. TypeName = Typename.replaceall ("", ""); //Replace full-width spaces
  68. brandname = Brandname.replaceall ("/", "" "); //Remove "/"
  69. brandname = Brandname.replaceall ("", ""); //Replace half-width spaces
  70. brandname = Brandname.replaceall ("", ""); //Replace full-width spaces
  71. File Firstfolder = new File ("c:/" + typeName); //First-level folders
  72. If (Firstfolder.exists ()) { //If the first-level folder exists, the level Two folder is detected
  73. File Secondfolder = new File (Firstfolder,brandname);
  74. If (Secondfolder.exists ()) { //If the Level two folder also exists, create the file
  75. FILE = new file (Secondfolder,filename);
  76. }else { //If the Level two folder does not exist, create a Level two folder
  77. Secondfolder.mkdir ();
  78. FILE = new file (Secondfolder,filename); //After you create a level two folder, then close the file
  79. }
  80. }else { //If the level does not exist, create a level folder
  81. Firstfolder.mkdir ();
  82. File Secondfolder = new File (Firstfolder,brandname);
  83. If (Secondfolder.exists ()) { //If the Level two folder also exists, create the file
  84. FILE = new file (Secondfolder,filename);
  85. }else { //If the Level two folder does not exist, create a Level two folder
  86. Secondfolder.mkdir ();
  87. FILE = new file (Secondfolder,filename);
  88. }
  89. }
  90. return file;
  91. }</pre>
  92. <p>
  93. </p><p> The above code basically implements the function we want. Of course, there are still many problems, the current has only reached a preliminary function, and did not write very rigorous. I'll cover the following articles about how to use JavaScript to implement thumbnails in the foreground! </p>
  94. <p> </p>
  95. <p> </p>
  96. <p> </p>
  97. <p> </p>

Uploading image files using spring MVC

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.