django文件上传的几种方式

方式一:通过form表单中,html input 标签的“file”完成

1
2
3
4
5
6
# 前端代码uoload.html
     <form method = "post"  action = "/upload/"  enctype = "multipart/form-data" >
         < input  id = "user"  type = "text"  name = "user"  / >
         < input  id = 'img'  type = "file"  name = "img"  / >
         < input  type = "submit"  / >
     < / form>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# 后端代码
def  upload(request):
     if  request.method  = =  'POST' :
         ret  =  { 'status' False 'data' None 'error' None }
         try :
             user  =  request.POST.get( 'user' )
             img  =  request.FILES.get( 'img' )
             =  open (os.path.join( 'static' , img.name),  'wb' )
             for  chunk  in  img.chunks(chunk_size = 1024 ):
                 f.write(chunk)
             ret[ 'status' =  True
             ret[ 'data' =  os.path.join( 'static' , img.name)
         except  Exception as e:
             ret[ 'error' =  e
         finally :
             f.close()
             return  HttpResponse(json.dumps(ret))
     return  render(request,  'upload.html' )

方法二:利用XmlHttpRequest对象,发送原生的Ajax请求

    (这种方法不能发送文件,需要依赖另外一个对象FormData)

  XmlHttpRequest对象的主要属性和方法

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
< input  type = "button"  value = "XMLHttpRequest按钮"  onclick = "XHRAjax();" >
 
<script>
         function XHRAjax() {
             var xhr  =  new XMLHttpRequest();
             xhr.onreadystatechange  =  function () {  # 回调函数--每当请求变化时,都会被触发,比如:创建、open、send、recv等。
                 if (xhr.readyState  = =  4 ){    # 仅当服务器数据全部返回时触发
                     var data  =  xhr.responseText;
                     console.log(data)
                 }
             };
             / /  GET请求
             / /  xhr. open ( 'GET' '/xhr_ajax?p=123' );
             / /  xhr.send();
             / /  POST请求
             xhr. open ( 'POST' '/xhr_ajax/' );   # 这里的URL必须加斜杠结尾。 发送post请求的时候必须携带请求头
             xhr.setRequestHeader( 'Content-Type' 'application/x-www-form-urlencoded; charset-UTF-8' );
             / /  发送请求
             xhr.send( 'n1=1;n2=2;' );
         };
< / script>

 

1
2
3
4
def  ajax(request):
     import  time
     current_time  =  time.time()
     return  render(request,  'ajax.html' , { 'current_time' : current_time})

  上述的内容,已经可以完成原生ajax的发送。 如果需要发送文件,则需要借助于FormData对象.下边介绍一下FormData的简单用法

1
2
3
# 前端代码
 
< input  type = "button"  value = "XMLHttpRequest-FormData按钮"  onclick = "XHRAjaxForm();" >
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# 后端代码: 基于FormData对象发送请求
function XHRAjaxForm() {
             var xhr  =  new XMLHttpRequest();
             xhr.onreadystatechange  =  function () {
                 if (xhr.readyState  = =  4 ){
                     var data  =  xhr.responseText;
                     console.log(data)
                 }
             };
             xhr. open ( 'POST' '/xhr_ajax/' );
             / /  发送请求
             var form  =  new FormData();   # 创建FormData对象
             form.append( 'user' 'alex' );
             form.append( 'pwd' '123' );
             xhr.send(form);
         };

  上面的例子,简单的介绍了FormData的用法 。下边的案例介绍如何使用formdate对象来上传文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# 前端部分
<a onclick = "uploadfile1();"  style = "cursor: pointer; display: inline-block;background-color: aqua" >XMLHttpRequet上传< / a>
 
# JS部分
<script>
       function uploadfile1() {
             var form  =  new FormData();
             form.append( 'user' , document.getElementById( 'user' ).value);
 
             var fileobj  =  document.getElementById( 'img' ).files[ 0 ];
             form.append( 'img' , fileobj);
 
             var xhr  =  new XMLHttpRequest();
             xhr.onreadystatechange  =  function () {
                 if (xhr.readyState  = =  4 ){
                     var data  =  xhr.responseText;
                     console.log(data)
                 }
             };
             xhr. open ( 'post' '/upload/' , true)
             xhr.send(form);
         }
< / script>

方法三:利用JQuery Ajax + FormData进行文件上传

  Jquery转换为dom对象:$("#img")[0].files[0];   其中$("#img")是jquery对象, $("#img")[0]是dom对象

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<a onclick = "uploadFile2();"  style = "cursor: pointer; display: inline-block;background-color: aqua" >JQuery - Ajax上传< / a>
 
<script>
 
         function uploadFile2() {
             var fileobj  =  $( "#img" )[ 0 ].files[ 0 ];
             console.log(fileobj);
             var form  =  new FormData();
             form.append( "img" , fileobj);
             form.append( "uesr" 'alex' );
             $.ajax({
                 type 'POST' ,
                 url:  '/upload/' ,
                 data: form,
                 processData: false,  # 告诉jquery要传输data对象
                 contentType: false,    # 告诉jquery不需要增加请求头对于contentType的设置
                 success: function (arg) {
                     console.log(arg)
                 }
             })
         }
< / script>

方法四:基于Iframe 实现伪Ajax 上传文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
<a onclick = "uploadFile3();"  style = "cursor: pointer; display: inline-block;background-color: aqua" >IFrame上传< / a>
 
 
 
<script>
         function uploadFile3() {
             / /  target 是个name的属性值,而不是 id
             $( "#container" ).find( 'img' ).remove();
             document.getElementById( "my_iframe" ).onload  =  callback;
             document.getElementById( 'fo' ).target  =  'my_iframe' ;
             document.getElementById( 'fo' ).submit();
         }
         function callback() {
             var t  =  $( '#my_iframe' ).contents().find( 'body' ).text();
             var json_data  =  JSON.parse(t);
             console.log(json_data);
             if (json_data.status){
                 / /  上传成功
                 var tag  =  document.createElement( 'img' );
                 tag.src  =  "/"  +  json_data.data;
                 tag.className  =  'img' ;
                 $( '#container' ).append(tag);
 
             } else {
                 / /  上传失败
                 console.log(status.error);
             }
 
         }
< / script>

  不是所有的浏览器都可以兼容FormData对象。为了兼容性,引出iframe 的用法。

   iframe可以建立一个通道发送请求,利用iframe局部刷新的特性实现目标。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# 前端代码
<iframe name = "my_iframe"  style = "display: none;"  src = "">< / iframe>
# 这里使用的是name标签,和id标签无关
 
 
<a onclick = "uploadFile3();"  style = "cursor: pointer; display: inline-block;background-color: aqua" >IFrame上传< / a>
 
<div  id = "container" >< / div>
 
     <script>
         function uploadFile3() {
             / /  target 是个name的属性值,而不是 id
             $( "#container" ).find( 'img' ).remove();
             document.getElementById( "my_iframe" ).onload  =  callback;  # 通过js手动绑定一个事件
             document.getElementById( 'fo' ).target  =  'my_iframe' ;    # 这里target对应的是一个iframe 的name属性
             document.getElementById( 'fo' ).submit();
         }
         function callback() {
             var t  =  $( '#my_iframe' ).contents().find( 'body' ).text();
             var json_data  =  JSON.parse(t);
             console.log(json_data);
             if (json_data.status){  
                 / /  上传成功
                  var tag  =  document.createElement( 'img' );
                 tag.src  =  "/"  +  json_data.data;
                 tag.className  =  'img' ;
                 $( '#container' ).append(tag);
 
             } else {
                 / /  上传失败
                 console.log(status.error);
             }
 
         }
 
< / script>

猜你喜欢

转载自www.cnblogs.com/jeavy/p/10886685.html