上传文件、ajax上传文件

一、普通上传文件

1 后台

from django.shortcuts import render,HttpResponse

# Create your views here.
def login(request):
    if request.method == 'GET':
        return render(request, 'login.html')


def fileupload(request):
    myfile=request.FILES.get('myfile')
    with open(myfile.name,'wb')as f:
        for line in myfile:
            f.write(line)
    return HttpResponse('上传成功')
View Code

2 配置url

3 前端

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <script src="/static/jquery-3.3.1.js"></script>
    <title>Title</title>
</head>
<body>
<form action="/fileupload/" method="post" enctype="multipart/form-data">
    <p>名字:<input type="text" name="name"></p>
    <p>文件:<input type="file" name="myfile"></p>
    <p><input type="submit" value="提交"></p>
</form>
</body>
</html>
View Code

二、ajax上传文件

1.后台

def fileupload(request):
    myfile=request.FILES.get('myfile')
    with open(r'D:\iii\o\p','wb')as f:
        for line in myfile:
            f.write(line)
    return HttpResponse('上传成功')
View Code

2 配置url

3 前端

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <script src="/static/jquery-3.3.1.js"></script>
    <title>Title</title>
</head>
<body>
<h1>ajax上传文件</h1>
<p>名字:<input type="text" id="id_name"></p>
<p>文件:<input type="file" id="id_file"></p>
<button id="filebtn">ajax上传文件</button>
</body>
<script>
    $("#filebtn").click(function () {
        var myfile=$("#id_file")[0].files[0]
        var formdata=new FormData()
        formdata.append('name',$("#id_name").val())
        formdata.append('myfile',myfile)
        $.ajax({
            url:/fileupload/,
            type:'post',
            processData:false,
            contentType:false,
            data:formdata,
            success:function (data) {
                console.log(data)
            }
        })
    })
</script>
</html>
View Code

 

posted @ 2019-01-18 20:27  葛洪  阅读(2337)  评论(0编辑  收藏  举报