二十二 .Django上传文件和AJAX文件上传

一. Django上传文件和AJAX文件上传

1. 普通文件上传

HTML
<!DOCTYPE html> <html lang="en"> <head> {% load staticfiles %} <meta charset="UTF-8"> <title>Title</title> <script type="text/javascript" src="{%static 'webpage/js/jquery1.js'%}"></script> </head> <body> <form action="{% url "aa" %}" method="post" enctype="multipart/form-data"> {% csrf_token %} <p><input type="text" name="aa"></p> <p><input type="file" name="img"></p> <input type="submit" value="上传"> </form> </body> </html>
VIEWS

from django.shortcuts import render,HttpResponse,render_to_response,redirect
import os
from django.conf import settings

def ajax_show(request):
      if request.method=="GET":
           return  render(request,"01html/04ajax_show.html")
      elif request.method=="POST":
             aa=request.POST.get("aa")
             img = request.FILES.get("img")
             print(img.name)  # 文件呢内容
             print(img.size)  # 文件大小

             f=os.path.join(settings.MDEIA_ROOT,img.name)    # 文件在服务器的路径
             o = open(f, "wb")
             for i in img.chunks():  # chunks()  这个函数表示上传文件一段一段的上传
                   o.write(i)
             o.close()
             return HttpResponse("ok")
print(os.path.join(settings.MDEIA_ROOT))  # J:\orm\02Dorm\webpys\myapp\statics\upfile
print(request.get_full_path()) # /home/ajax_show/
def upload_file(request): 
    if request.method == "POST":    # 请求方法为POST时,进行处理 
        myFile =request.FILES.get("myfile", None)    # 获取上传的文件,如果没有文件,则默认为None 
        if not myFile: 
            returnHttpResponse("no files for upload!") 
        destination = open(os.path.join("E:\\upload",myFile.name),'wb+')    # 打开特定的文件进行二进制的写操作 
        for chunk in myFile.chunks():      # 分块写入文件 
            destination.write(chunk) 
        destination.close() 
        returnHttpResponse("upload over!") 

 2. ajax文件上传

猜你喜欢

转载自www.cnblogs.com/lovershowtime/p/11371245.html
今日推荐