博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
实现文件上传的多种方法
阅读量:6937 次
发布时间:2019-06-27

本文共 2001 字,大约阅读时间需要 6 分钟。

 

实现文件上传的多种方法

 

一、Form表单上传

    
上传文件
{% csrf_token %}

  

def update(request):    if request.method=="GET":        return render(request,'update.html')    else:        img=request.FILES.get('img')        if img:            print(img.name)            print(img.size)            f = open(img.name, "wb")            for line in img.chunks():                f.write(line)            f.close()            return HttpResponse('上传成功')        else:            return HttpResponse('选择上传文件')

 

 

二、AJAX上传

HTML - XMLHttpRequest

获取数据:var fileObj = document.getElementById("img").files[0]; 封装数据:var form = new FormData(); form.append("k1", "v1"); form.append("fff", fileObj);注意:FormData是个用来封装数据的。 创建XMLHttpRequest:var xhr = new XMLHttpRequest(); 发送数据:
xhr.open("post", '/index', true); xhr.send(form);

  

    
HTML - XMLHttpRequest

  

 

HTML - jQuery

1.这里使用ajax进行数据提交 2.需要加上这两条  processData: false,  // tell jQuery not to process the data contentType: false,  // tell jQuery not to set contentType

  

 

    
HTML - jQuery

  

  

 HTML - iframe

    

  

 

 演示图片上传功能(iframe+From)

    
Title {% load staticfiles %}

预览

View Code

 

from django.shortcuts import render, HttpResponse, redirectimport jsonimport osimport uuiddef upload_img(request):    nid = str(uuid.uuid4())    ret={
'status':True,'data':None,'message':None} obj=request.FILES.get('File') file_path=os.path.join('static',nid+obj.name) print(file_path) print(1) f=open(file_path,'wb') for line in obj.chunks(): f.write(line) f.close() ret['data']=file_path return HttpResponse(json.dumps(ret))
View Code

 

 

 

 

转载于:https://www.cnblogs.com/-wenli/p/10527203.html

你可能感兴趣的文章