1 Save the file to the server local upload.html
<! DOCTYPE html>
urls.pyFrom django.conf.urls import urlfrom app01 Import viewsurlpatterns = [ url (R ' ^upload ', views.upload)]
views.pyFrom django.shortcuts import render,httpresponsedef 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 ')
SummarizeIn this way, we have done a basic file upload small example, here are a few things to note:
- Need to add Csrf_token validation to form forms
- The value of the type of the file's input box is file
- To get a file in a view function, use request. Files.get () method
- The name of the file can be obtained by obj.name
2 uploading files to the database models.pyFrom django.db import Modelsclass User (models. Model): username = models. Charfield (max_length=16) avatar = models. Filefield (upload_to= ' Avatar ')
views.pydef 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 ')
SummarizeThe above has implemented the ability to upload files to the database, there are several points to note:
- The so-called upload to the database, not to tell the picture itself or binary stacking in the database, and actually upload the file to the server locally, the database is just a path to save a file, so that the user can call the file by the path to the server designated location to find
- When creating an ORM, the Avatar field must have a property of upload_to= ', specifying where the uploaded file is placed
- When adding to the database, the File field property assignment is the same as the normal field, such as: models. User.objects.create (Username=name,avatar=avatar)
- If two users upload a duplicate file name, the system will automatically rename the files, the effect is as follows:
AdditionalFunction We are implemented, it seems that when we call the file, only through the database file path has been saved by the file itself can access the picture, let it appear on the Web page, in fact, it is not so,
We need to configure something, Django can find it, otherwise it will not be able to get through the URLs verification, and we can directly access static files in static, because Django has been configured for us.
The configuration steps are as follows:
1, in the site of the setting.py configuration
Media_root=os.path.join (Base_dir, "blog", "Media") #blog是项目名, Media is the agreed idiomatic folder name media_url= "/media/" # with Static Similar to _url, the specified user can find the file through this path
2, in the urls.py configuration
From django.views.static import servefrom upload import Settings #upload是站点名url (R ' ^media/(? p<path>.*) $ ', serve, {' Document_root ': Settings. Media_root}),
Once configured, you will be able to access the image via Http://127.0.0.1:8001/media/milk.png.
3 Submitting files with Ajax upload.html<! DOCTYPE html>
Formdata.append ("Avatar", $ ("#avatar") [0].files[0]);
$.ajax ({
Processdata:false,
if (arg.state = = 1) {alert (' Success! ')}else {alert (' failed! ‘) } } }) });
</script> </body>
views.pyFrom django.shortcuts import render,httpresponsefrom django.http import jsonresponsefrom app01 import modelsdef 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 ')
Summarize
- Ajax upload, the button Tpye must not use the Submit
- When Ajax uploads, the value of the data parameter is no longer a normal ' dictionary ' type value, but a formdata
- Create Object FormData = new FormData ();
- Add the value formdata.append (' username ', $ (' #name-input ') to the inside. Val ());
- Ajax to add CSRF verification when doing post submission
- Formdata.append ("Csrfmiddlewaretoken", $ ("[name= ' Csrfmiddlewaretoken ']"). Val ());
- Finally, Ajax uploads a file with two parameter settings
-
- Processdata:false
- Contenttype:false
4 Preview function when uploading image files
<! DOCTYPE html>5 Big summariesFor file upload, whether it is a direct form submission or AJAX submissions, the fundamental problem is to tell the browser that you want to upload a file instead of a normal string
And how to tell the browser, that is, by asking for the weight of the contenttype parameter, we upload the normal string without specifying, because it has a default value,
And if you want to pass the file, you have to specify it separately. Summarize the following points
- The form forms are uploaded by enctype= "Multipart/form-data" to specify ContentType
- Ajax uploads are specified by processdata:false and Contenttype:false ContentType
- When the form is uploaded, the file data is "wrapped" by <input type= "file" > tag.
- When Ajax uploads, the data is added via an FormData instance object, which is passed when the object is passed.
- After the data is passed through, it is encapsulated in the request. Files , not request. In post
User avatar upload and access for Django Project combat