1. 程式人生 > >上傳文件、ajax上傳文件

上傳文件、ajax上傳文件

submit display gin lap 成功 eth pre views ssd

一、普通上傳文件

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(rD:\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

上傳文件、ajax上傳文件