文件上传&ContentType请求格式

一、文件上传

1、通过表单形式上传文件

1 <form action=' /file_put/' method='post' enctype=' multipart/form-data'>                                                                 
2     文件名<input type='file' name='file_obj'>
3              <input type='submit'>
4 </form>

表单上传文件需要设置属性:enctype

url.py 文件路径如下:

  path('file_put',views.file_put)

视图函数

 1 def file_put(request):
 2     #获取到上传的文件对象
 3     file_obj=request.FILES.get('file_obj')
 4     #文件有一个name属性,获取文件名称字符串
 5     print(file_obj.name)
 6     path=file_obj.name
 7   #拼接路径
 8     path=os.path.join(settings.BASE_DIR,'media','img',path)
 9     with open(path,'wb') as f :
10         for line in file_obj:
11             f.write(line)
12     
13     return HttpResponse('ok')

2、通过Ajax上传文件

 1 文件<input type="file" name="file_obj" id="file">
 2 <input type="button" class="filbtn" value="提交">
 3 <p class="msg"></p>
 4 
 5 <script>
 6     $(function () {
 7         $('.filbtn').click(function () {
 8             var formdata=new FormData();
 9             //拼键值对('file_obj':'$('#file')[0].files[0]')
10             //$('#file')[0].files[0]是根据id找到文件
11             formdata.append('file_obj',$('#file')[0].files[0]);
12             $.ajax({
13                 url:'/app01/file_put/',
14                 type:'post',
15                 // Ajax上传文件必备参数
16                 processData: false ,    // 不处理数据
17                 contentType: false,    // 不设置内容类型
18                 data:formdata,
19                 success:function (response) {
20                     if(response=='ok'){
21                         $('.msg').html('上传成功')
22                     }
23                 }
24 
25 
26             })
27         })
28     })
29 </script>

视图函数同上

 二、contentType

contentType在请求头里,告诉浏览器是什么请求格式,

请求格式的分类

  urlencoded:默认的请求格式 use='bart'&pwd='123'

  formdata:上传文件

  json格式:{‘use’:'Andey','pwd':123}

 1 $.ajax({
 2     url:'',
 3     type:post,
 4     contentType:'json',
 5     #序列化发送
 6     data:JSON.stringify({
 7         key1:value,
 8         key2:value,
 9     
10     })
11     
12      processData: false ,    // 不处理数据
13      contentType: false,    // 不设置内容类型
14 
15 
16 })

注:

  Django 只解析URLencoded格式的数据
  发送json数据只能手动解
  解析json数据:
  data=request.body.decode('utf8)解码
  json_data=json.loads(data) 反序列化

原文地址:https://www.cnblogs.com/liaopeng123/p/9879869.html