上传文件ajax上传文件
Posted 葛洪
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了上传文件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(‘上传成功‘)
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>
二、ajax上传文件
1.后台
def fileupload(request): myfile=request.FILES.get(‘myfile‘) with open(r‘D:iiiop‘,‘wb‘)as f: for line in myfile: f.write(line) return HttpResponse(‘上传成功‘)
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>
以上是关于上传文件ajax上传文件的主要内容,如果未能解决你的问题,请参考以下文章