文件 jq 传到后台


 

XMLHttpRequest Level 2 添加了一个新的接口——FormData。与普通的 Ajax 相比,使用 FormData 的最大优点就是我们可以异步上传二进制文件。

jQuery 2.0+的版本支持FormData

方法一:使用<form>表单初始化FormData对象方式上传文件

•前端(JQuery):

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<form enctype= "multipart/form-data" >
   <input type= "file" name= "myfile" onchange= "loadFile(this.files[0])" >
</form>
<script>
   function loadFile(file){
     var formdata = new FormData($$( 'form' )[0]);
     $.ajax({
       url: 'jobs/add' ,
       type: 'POST' ,
       datatype: 'json' ,
       data: formdata,
       cache: false ,
       traditional: true ,
       contentType: false ,
       processData: false ,
       success: function (data) {},
       error: function () {}
     });
   }
</script>

•后台(web.py):

?
1
2
3
4
5
6
class Add:
   def POST(self):
     i = web.input(myfile={})
     print(i[ 'myfile' ].filename) #文件名
     print(i[ 'myfile' ].value) #文件内容
     print(i[ 'myfile' ].file.read()) #文件内容

 注意:

1.<form>的enctype属性需要设置为“multipart/form-data”

2.$.ajax中processData、contentType和cache需要设置为false

3.后端通过web.input获取文件的字段名,同前端指定的input标签的name属性

方法二√:不用<form>,使用FormData对象添加字段方式上传文件

有时,我们并不想用

标签,而且通过ajax传给后端的并不只有文件,可能还有其他的键值对,这时就可以用这个方法

•前端(JQuery):

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<input type= "file" onchange= "loadFile(this.files[0])" />
function loadFile(file){
   container.fd = new FormData();
   container.fd.append( 'myfile' ,file);
   container.fd.append( 'otherkey' ,othervalue);
   $.ajax({
     url: 'jobs/add' ,
     type: 'POST' ,
     datatype: 'json' ,
     data: fd,
     cache: false ,
     traditional: true ,
     contentType: false ,
     processData: false ,
     success: function (data) {},
     error: function () {}
   });
}

•后台(web.py):

?
1
2
3
4
5
6
class Add:
   def POST(self):
     i = web.input(myfile={}, otherkey= '' )
     print(i[ 'myfile' ].filename) #文件名
     print(i[ 'myfile' ].value) #文件内容
     print(i[ 'myfile' ].file.read()) #文件内容

前台2:

 <input type="file" id="fileContent" onchange="file(this.files[0])" name="myfile"/>

    ////文件传到后台的方法
        function file(f)
        {
            debugger;
            var formData = new FormData();
            var name = $("input").val();
            formData.append("file", $("#fileContent")[0].files[0]);
            formData.append("name", f.name);
            $.ajax({
                url: 'TestHandler.ashx',
                type: 'post',
                data: formData,
                datatype:'JSON',
                fileElementId: 'fileContent',
                // 告诉jQuery不要去处理发送的数据
                processData: false,
                // 告诉jQuery不要去设置Content-Type请求头
                contentType: false,
                cache: false,
                traditional: true,
                success: function (data) {
                    $('#img').attr('src', data);
                }
            });
        }

  

后台2 :

HttpFileCollection files =context.Request.Files;
if (files != null && files.Count > 0)
{
////image 传的文件流
Image i = Image.FromStream(files[0].InputStream);
byte[] re = new byte[files[0].ContentLength];
files[0].InputStream.Read(re, 0,files[0].ContentLength);


string name=files[0].FileName;
string path = @"C:\Users\duxiaoqin\Desktop\" + name;
i.Save(path);
context.Response.Write(path);
context.Response.End();
}

  

注意:

1.没有<form>标签(有了也不错)

2.append()方法的第二个参数是文件对象,在html中已经通过loadFile方法的参数传过来

3.后端通过web.input获取文件的字段名,同前端append()方法的第一个参数

4.因为通过web.input获取的值都是字符串,如果除文件以外的键值对传过来是null,会自动转化为字符串'null'。这点处理的时候需要注意

以上所述是小编给大家介绍的jQuery Ajax使用FormData上传文件和其他数据后端web.py获取,希望对大家有所帮助,如果大家有任何疑问欢迎给我留言,小编会及时回复大家的




免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM