Home > Article > Backend Development > Django project practical user avatar upload and access
This article mainly introduces the practical examples of uploading and accessing user avatars in Django projects. Now I share them with you and give them a reference. Let’s take a look together
1 Save the file locally on the server
upload.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> </head> <body> <form action="" method="post" enctype="multipart/form-data"> {% csrf_token %} <p>用户名:<input type="text" name="username"></p> <p>头像<input type="file" name="avatar"></p> <input type="submit" value="提交"> </form> </body> </html>
urls.py
from django.conf.urls import url from app01 import views urlpatterns = [ url(r'^upload',views.upload) ]
views.py
from django.shortcuts import render,HttpResponse def upload(request): if request.method == 'POST': name = request.POST.get('username') avatar = request.FILES.get('avatar') with open(avatar.name,'wb') as f: for line in avatar: f.write(line) return HttpResponse('ok') return render(request,'upload.html')
Summary
In this way, we have made a basic small example of file upload. There are a few points to note here:
1. The form requires Add csrf_token verification
2. The type value of the input box of the file is file
3. To obtain the file in the view function, use the request.FILES.get() method
4. Through obj.name Get the name of the file
2 Upload the file to the database
models.py
from django.db import models class User(models.Model): username = models.CharField(max_length=16) avatar = models.FileField(upload_to='avatar')
views.py
def upload(request): if request.method == 'POST': name = request.POST.get('username') avatar = request.FILES.get('avatar') models.User.objects.create(username=name,avatar=avatar) return HttpResponse('ok') return render(request,'upload.html')
Summary
The function of uploading files to the database has been implemented above. There are a few points to note:
1. The so-called uploading to the database does not mean placing the image itself or the binary code in the database. It actually uploads the file to the server locally. The database only stores the path of a file, so that when the user wants to call the file, he can go to the location specified by the server through the path.
2. When creating the ORM, the avatar field must have an upload_to='' attribute, specify Where to put the uploaded files
3. When adding to the database, the file field attribute assignment is the same as the ordinary field in form, such as: models.User.objects.create(username=name,avatar=avatar)
4. If there are duplicate file names uploaded by two users, the system will automatically rename the file, with the following effect:
##Append
MEDIA_ROOT=os.path.join(BASE_DIR,"blog","media") #blog是项目名,media是约定成俗的文件夹名 MEDIA_URL="/media/" # 跟STATIC_URL类似,指定用户可以通过这个路径找到文件2. Configure in urls.py
from django.views.static import serve from upload import settings #upload是站点名 url(r'^media/(?P<path>.*)$', serve, {'document_root': settings.MEDIA_ROOT}),After configuring, you can pass http://127.0.0.1:8001/media/milk.png accessed the picture
3 Use AJAX to submit the file
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> </head> <body> <form> {% csrf_token %} <p>用户名:<input id="name-input" type="text"></p> <p>头像<input id="avatar-input" type="file"></p> <input id="submit-btn" type="button" value="提交"> </form> <script src="/static/js/jquery-3.2.1.min.js"></script> <script> $('#submit-btn').on('click',function () { formdata = new FormData(); formdata.append('username',$('#name-input').val()); formdata.append("avatar",$("#avatar")[0].files[0]); formdata.append("csrfmiddlewaretoken",$("[name='csrfmiddlewaretoken']").val()); $.ajax({ processData:false,contentType:false,url:'/upload', type:'post', data:formdata,success:function (arg) { if (arg.state == 1){ alert('成功!') } else { alert('失败!') } } }) }); </script> </body> </html>views.py
from django.shortcuts import render,HttpResponse from django.http import JsonResponse from app01 import models def upload(request): if request.method == 'POST': name = request.POST.get('username') avatar = request.FILES.get('avatar') try: models.User.objects.create(username=name,avatar=avatar) data = {'state':1} except: data = {'state':0} return JsonResponse(data) return render(request,'upload.html')Summary
2. When Ajax uploads, the value of the data parameter is no longer an ordinary 'dictionary' type value, but a FormData object
4 There is a preview function when uploading image files
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> </head> <body> <form> <!----用一个label标签将上传文件输入框跟图片绑定一起, 点击图片的时候就相当于点击了上传文件的按钮----> <label><img id="avatar-img" src="/static/img/default.png" width="80px" height="80px"> <p>头像<input id="avatar-input" hidden type="file"></p> </label> <input id="submit-btn" type="button" value="提交"> </form> <script src="/static/js/jquery-3.2.1.min.js"></script> <script> // 上传文件按钮(label里的图片)点击事件 $('#avatar-input').on('change',function () { // 获取用户最后一次选择的图片 var choose_file=$(this)[0].files[0]; // 创建一个新的FileReader对象,用来读取文件信息 var reader=new FileReader(); // 读取用户上传的图片的路径 reader.readAsDataURL(choose_file); // 读取完毕之后,将图片的src属性修改成用户上传的图片的本地路径 reader.onload=function () { $("#avatar-img").attr("src",reader.result) } }); </script>##5 Summary
For file upload, whether it is direct form submission or Ajax submission, the fundamental problem is to tell the browser that what you want to upload is a file instead of an ordinary string
What about We tell the browser by requesting the ContentType parameter of the weight. We don’t need to specify it when uploading a normal string, because it has a default value,
. And if you want to upload a file, you need to specify it separately. . Summarize the following points
2. For ajax upload, ContentType is specified through processData:false and contentType:false
3. When the form is uploaded, the file data is "wrapped" through the 3525558f8f338d4ea90ebf22e5cde2bc tag.
4. When the ajax is uploaded, the data is added through a FormData instance object. Just pass this object when passing it
5. After the data is passed, it is encapsulated in request.FILES instead of request.POST
Related recommendations:
How Django loads css and js files and static images
Detailed explanation of the use of django controls and parameter passing
The above is the detailed content of Django project practical user avatar upload and access. For more information, please follow other related articles on the PHP Chinese website!