Ajax achieve attachment upload

 The first two articles have introduced the use of form.submit to upload attachments, but this approach is very easy to use, such as over the future need to perform a successful upload some other operations too much trouble. Let me introduce the next use ajax to achieve attachment upload function:

1. FormData objects upload file:

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <script src="https://cdn.bootcss.com/jquery/1.10.2/jquery.min.js"></script>
    <title></title>
</head>
<body>
    文件:<input id="file" type="file" name="file"/>
<button id="upload">上传文件</button>
</body>
<script type="text/javascript">
    $(function () {
        $("#upload").click(function () {
            var formData = new FormData();
data.append("file", $("#file")[0].files[0]); $.ajax({ type:
'post', url: "XXX", Data: formdat to, cache: false, processData: false, contentType: false, }).success(function (data) { alert(data); }).error(function () { alert("上传失败"); }); }); }); </script> </html>  

Parameters: 1, processData set to false. Because the data values ​​are FormData objects, the data need not be processed. Data processing because it is object type, jquery will not be processed in a processing error;

                  2, cache set to false, you do not need to upload the file cache.

                  3, contentType set to false. Because the form is constructed FormData objects, and has been declared attribute enctype = "multipart / form-data", it is here set to false.

But this FormData objects only in high versions of IE support in the lower version of IE is not supported FormData objects, this method is compatible with the following versions of IE problem of low and high versions of IE upload attachments can be achieved

2, form.ajaxSubmit submit a request, this method requires a reference jquery.Form.js this library can, otherwise it can not be used ajaxsubmit

                  <label for="btn_file">上传附件</label>
                 <form id="form" method="post" enctype="multipart/form-data">
                    <input type="file" id="btn_file" name="file" onchange="fileUpload()">
                 </form>
  function fileUpload()
    {
        $('#form').ajaxSubmit({
            type: "post",
            url: "XXX.do?",//请求的 URL地址
            data: $('#form').serialize(),
            error: function (data) {
                alert(data);
            },
            success: function (data) {
                var result = eval('(' + data + ')');
                if (result.success) {
                  alert(result.res);
                }
            }
        });
}

 

Guess you like

Origin www.cnblogs.com/mingqi-420/p/10950573.html