How do I submit an image file in the Layui Quick Start form form? _ajax

Source: Internet
Author: User
Tags button type file url
Objective

The form form contains files, such as image files, normal text files, audio and video files, what to do.
There are two total solutions: use Formdata to implement files and text at the same time to submit the first Ajax upload file, return the file URL, and then submit with the text, I called perjury submitted.

This article mainly introduces the second kind of pseudo submission scheme, the Formdata use tutorial is listed below.
Https://developer.mozilla.org/zh-CN/docs/Web/API/FormData/Using_FormData_Objects body

1, this article development environment:

 1. Spring boot
 2. mysql
 3. Java
 4. Thymeleaf template engine
 5. Layui Library

2, Layui use tutorial
Note: Layui has a upload module, especially handy, this article is the use of upload module to achieve the goal. The official documentation for the upload module is detailed, so I suggest you study the official document and see my example later.
Loading of Layui modules
http://www.layui.com/doc/
Picture/File Upload-layui.upload
Http://www.layui.com/doc/modules/upload.html#choose

3, before and after the table code
Front page code:

<form class= "Layui-form" enctype= "Text/plain" > <div class= "Layui-form-item" > <label class= "Lay" Ui-form-label "> Name </label> <div class=" Layui-input-block "> <input name=" name "Lay-ve rify= "name" autocomplete= "Off" placeholder= "Please enter title" class= "Layui-input" type= "text"/> </div> </div&

    Gt <div class= "Layui-form-item" > <label class= "Layui-form-label" > Photos </label> <div class= "
            Layui-input-block "> <button type=" button "class=" layui-btn "id=" upload1 "> Upload photos </button>
                <input type= "hidden" id= "Img_url" Name= "img" value= ""/> <div class= "Layui-upload-list" >  <p id= "Demotext" ></p> </div> </div> </div> <div class= "Layui-form-item" style= " Text-align:center; " > <button type= "Submit" class= "LAYUI-BTN" onclick= "Update" value= "save"/> <button class= "Layui-b" TN "lay-submit=" "lay-filter=" * "> Submit now </button> </div> </form>

Let's take a look at the following code that involves uploading files. The div contains a button, a hidden input (for saving the file URL), and a specially-previewed div.

        <div class= "Layui-input-block" >
            //Upload button
            <button type= "button" class= "layui-btn" id= "Upload1" > Upload pictures </button>/
            /Hidden input
            <input type= "hidden" id= "Img_url" Name= "img" value= ""/>
            //preview area
            <div class= "layui-upload-list" >
                
                <p id=" Demotext "></p>
            </div>
        </div>

First on the effect chart

OK, now let's go ahead, on the JS code. In this JS code, the most core thing only three loading upload upload module to my button plus upload file function upload success, the return URL saved to the hidden input

<script type= "Text/javascript" th:inline= "JavaScript" > Layui.use (' Upload ', function () {var upload = Layu
        I.upload, $ = layui.jquery;
            var uploadinst = Upload.render ({elem: ' #upload1 '//binding element, URL:/*[[@{/upload/img}]]*/'//upload interface , Before:function (obj) {//Pre-read file example does not support IE8 Obj.preview (function (index, file, Resul
            T) {$ (' #demo1 '). attr (' src ', result);//Picture Link (base64)}); Done:function (res) {//If upload failed if (Res.code > 0) {retu
                RN layer.msg (' upload failed ');
                //Upload Success alert ("Upload success" +res.url);

            document.getElementById ("Img_url"). Value = Res.url;
                }, Error:function () {//Demo failed state and implement retransmission var Demotext = $ (' #demoText '); Demotext.html (' <span style= "color: #FF5722;" > upload failed </span> <a class= "layui-btn layui-btn-mini demo-reload" > Retry </a> ');
                Demotext.find ('. Demo-reload '). On (' click ', Function () {uploadinst.upload ();
            });
    }
        });
});
 </script>

File Upload Controller

@Controller @MultipartConfig public class Fileuploadcontroller {@RequestMapping (value = "/upload/img"), method = Req
                         Uestmethod.post) @ResponseBody public map<string, object> upload (HttpServletRequest servletrequest, @RequestParam ("file") Multipartfile file) throws IOException {//if file Content is not empty, write upload path if (!file.isempty ()) {//Upload file path String path = "/home/jian/desktop/qingyunv2/

            Qingyunv2/src/main/resources/static/images ";
            System.out.println ("File name" +file.getoriginalfilename ());
            Upload filename String filename = file.getoriginalfilename ();


            File filepath = new file (path, filename); To determine if the path exists, do not create an if (!filepath.getparentfile (). exists ()) {Filepath.getparentfile (). Mkdirs ()
            ;
            //Save the uploaded file to a target document file File1 = new file (path + file.separator + filename); FilE.transferto (FILE1);
            map<string, object> res = new hashmap<> ();
            Returns a URL object res.put ("url", file1);

        return res;
        else {return result.failure ();
 }

    }
}

Now that the file upload task has been completed, the hidden input in the form has already saved the URL of the file, then the simple plain text form submission is next. This is not difficult, with Ajax submission line, the normal submission can also be arbitrary. Below, I just post the code.

Ajax Submit Plain Text form

<!--to add th:inline= "JavaScript" to the current script, tymeleaf can take effect.
    self.location =/*[[@{/sys_seller/find}]]*/';--> <script type= ' text/javascript ' th:inline= ' JavaScript ' >  Layui.use ([' Form ', ' layedit '], function () {var form = layui.form, layer = Layui.layer, $
        = Layui.jquery; Form.on (' Submit (*) ', function (data) {$.ajax ({type: ' POST ', url:/*[[@{/sys_ seller/add}]]*/', DataType: ' JSON ', data:data.field,//sent back the table is Data.field, that is, a {name:value} 
                        Data Structure async:true, success:function (Result) {if (Result.code = 0) {
                        Layer.msg (' Save Success ', {icon:1, time:1000});
                        settimeout (function () {self.location =/*[[@{/sys_seller/find}]]*/';
                    }, 800); else {layer.msg (' save failed. ' + result.msg, {icon:2, time:1000}); }, Error:function (result, type) {layer.msg (' save failed.
                ', {icon:2, time:1000});
        }
            });
        });
    return false;
}); </script>

Save Information Controller

    @RequestMapping (value = "/sys_seller/add") @ResponseBody public result Add (@RequestParam ("name") String name , @RequestParam ("ManagerName") String ManagerName, @RequestParam ("Phone") stri ng phone, @RequestParam ("tel") string tel, @RequestParam ("remark") string Rema  RK, @RequestParam ("Sellarrange") String Sellarrange, @RequestParam ("province") String province, @RequestParam (' City '), @RequestParam ("address")
        String address, @RequestParam ("img") string img) throws IOException {
        Sellers seller = new Sellers ();
        Seller.setname (name);
        Seller.setmanagername (ManagerName);
        Seller.setphone (phone);
        Seller.settel (tel);
        Seller.setremark (remark);
        Seller.setsellarrange (Sellarrange); Seller.setpRovince (province);
        Seller.setcity (city);
        Seller.setaddress (address);
        Seller.setimgurl (IMG);
        System.out.println (Seller.tostring ());
        Qingyunservice.saveseller (seller);
    return result.success (); }
Summary

This article only as a primer, too many things I also say do not understand, I hope that these will help you. If you want to get the full details of the submission, you need to know the basics of @responsebody and Ajax principles. You need to lay a good foundation before you can have a high building on the ground.

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.