Spring boot+bootstrap fileInput Multi-image upload

Source: Internet
Author: User

I. Dependent documents
<Linkrel= "stylesheet"type= "Text/css"Th:href= "@{/js/bootstrap/css/bootstrap.css}"><Linkrel= "stylesheet"type= "Text/css"Th:href= "@{/js/bootstrap/fileinput/css/fileinput.css}"><!--Join Fileinput -<Scriptth:src= "@{/js/jquery-3.3.1.min.js}"></Script><Scriptth:src= "@{/js/bootstrap/js/bootstrap.js}"></Script><Scriptth:src= "@{/js/bootstrap/fileinput/js/fileinput.js}"></Script><Scriptth:src= "@{/js/bootstrap/fileinput/js/zh.js}"></Script>/* Language Environment */

Second, form

<formclass= "form"Action="#"Method= "POST"enctype= "Multipart/form-data"ID= "Pollutionform">    <!--Note: The Input type type is file class for the style ID arbitrary name multiple (if you want to upload more than the image must be added, not add the words can only select one picture at a time) -Photo:<inputtype= "File"class= "File"ID= "img"Multiple name= "Images"><BR></form>

Third, JavaScript code

<script>/**/    varImageData = [];//multi-image upload returned picture properties Accept array This is because I am using the other properties of the form when I submit it, where I did not write the other input    $("#img"). Fileinput ({language:' En ', Uploadurl:"/image/save-test", Showupload:true,//whether to display the upload buttonShowremove:true,//Show Remove buttonShowpreview:true,//whether to show previewShowcaption:false,//whether to show titleAutoreplace:true, Minfilecount:0, Uploadasync:true, Maxfilecount:10,//maximum number of uploadsBrowseonzoneclick:true, Msgfilestoomany:"Choose the number of uploaded files that exceed the maximum allowed value!" ", Enctype:' Multipart/form-data ',        //overwriteinitial:false,//do not overwrite uploaded imagesAllowedfileextensions: ["JPG", "png", "GIF"], Browseclass:"Btn Btn-primary",//button StylePreviewfileicon: "<i class= ' Glyphicon glyphicon-king ' ></i>"}). On ("Fileuploaded",function(E, data) {//File Upload successful callback function, there are some other callback functions, such as before the upload ...        varres =Data.response; Console.log (res) Imagedata.push ({"Path": Res.data.path,"Date": Res.data.date});    Console.log (ImageData); });</script>

Four, backstage code

//Picture ClassImportjava.util.Date;/*** Picture Class*/ Public classIMG {PrivateString name; PrivateString Path; PrivateDate date;  PublicImg () {} PublicImg (String path, date date) { This. Path =path;  This. Date =date; }     PublicImg (string name, string path, date date) { This. Name =name;  This. Path =path;  This. Date =date; }     PublicString GetName () {returnname; }     Public voidsetName (String name) { This. Name =name; }     PublicString GetPath () {returnpath; }     Public voidSetPath (String path) { This. Path =path; }     PublicDate getDate () {returndate; }     Public voidsetDate (date date) { This. Date =date; } @Override PublicString toString () {return"img{" + "name=" + name + "\" + ", path=" + path + "\" + ", date=" + Date + '} '; }}//Image upload Controller Public classUploadcontroller {//fileinput In fact, each time only upload a file multi-image upload is also multiple requests, each upload a file so do not need to loop@RestController//@RequestParam ("Images") here the images corresponds to the name in the form and then the Multipartfile parameter name can be arbitrary.@RequestMapping (value = "/image/save-test", method =requestmethod.post) PublicUploadresponsedata saveimg (@RequestParam ("Images") multipartfile file)throwsIOException {String pathname= ""; String Returnpath= ""; if(!File.isempty ()) {String FileName=File.getoriginalfilename (); File Path=NewFile (Resourceutils.geturl ("Classpath:"). GetPath ());//gets the root path of the spring Boot project, which was acquired at development time by/target/classes/System.out.println (Path.getpath ());//If your picture storage path is static, you can refer to the following wordingFile UploadFile =NewFile (Path.getabsolutepath (), "static/images/upload/");//the/target/classes/static/images/upload/is obtained in the development test mode            if(!uploadfile.exists ())            {Uploadfile.mkdirs (); }            //get file suffix nameString end =filenameutils.getextension (File.getoriginalfilename ()); DateFormat DF=NewSimpleDateFormat ("Yyyymmddhhmmsssss"); //picture name take time stitching random numberString name = Df.format (NewDate ()); Random R=NewRandom ();  for(inti = 0; i < 3; i++) {Name+ = R.nextint (10); } String diskfilename= name + "." +end;//filename of the destination filepathname = Uploadfile.getpath () + "/" +Diskfilename;            SYSTEM.OUT.PRINTLN (pathname); Returnpath= "images/upload/" + diskfilename;//here is my own to do the return stringFile.transferto (NewFile (pathname));//file Dump}//Uploadresponsedata Custom Return data type entity {int code, String msg, Object data}        return NewUploadresponsedata (CodeEnum.SUCCESS.getCode (), MSGENUM.SUCCESS.GETMSG (),NewIMG (Returnpath,NewDate ())); }}

Five, summarize it

Finally, here are some questions to ask.
    1. The Spring boot path gets the problem:
     Resourceutils.geturl ("Classpath:"). GetPath (); The project root path is obtained in the development environment/target/class/

Resourceutils.geturl ("Classpath:/static/images/upload/"). GetPath (); Test Failed file UploadFile = new file (Path.getabsolutepath (), "static/images/upload/"); In the development environment,/target/class/images/upload/was acquired.After you deploy the Project Pack War package to Tomcat,/target/class/--and/web-inf/classes/, static/images/upload/--and /we b-inf/classes/static/images/upload/ 2, Fileinput need to have return parameter format arbitrary (not too casual ha)3, suddenly can't remember, if there will continue to more Six, if the wrong place, please also point out, thank you!

Spring boot+bootstrap fileInput Multi-image upload

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.