Recently in the development process with the Django framework encountered uploading user avatar problem, through a multi-party search data, finally solve the problem!
1. First, add code similar to the following in the HTML template
12345 |
< form enctype="multipart/form-data" method="POST" action="/view/process/upload/file"> {% csrf_token %} < input type="file" name="your_file"/> < input type="submit" value="上传文件" /> </ form > |
Here are a few things to look at:
- Form summary must have enctype= "Multipart/form-data" Property
- Form needs to be submitted by POST
- The Action property of the form corresponds to the function that handles upload upload logic in views
- Need to have csrf_token this tag, otherwise post cannot be submitted
- The first type of <input> is file, which is a document selector, and the Name property is important because the file object is later removed from this field
2. Next, write the CGI logic
1234567891011121314 |
def
process_upload_file(request):
# 获取文件
file_obj
=
request.FILES.get(
‘your_file‘
,
None
)
if
file_obj
=
=
None
:
return
HttpResponse(
‘file not existing in the request‘
)
# 写入文件
file_name
=
‘temp_file-%d‘
%
random.randint(
0
,
100000
)
# 不能使用文件名称,因为存在中文,会引起内部错误
file_full_path
= os.path.join(UPLOAD_ROOT, file_name)
dest
=
open
(file_full_path,
‘wb+‘
)
dest.write(file_obj.read())
dest.close()
return render_to_response(
‘upload_result.html‘
,{})
|
The file is taken in the following way: "file_obj = Request." Files.get (' file ', None) ". The first parameter "your_file" corresponds to the first input label in the form. You can then get the file name by File_obj.name, and the File_obj.read () method gets the file contents. The uploaded file is placed in memory, so this method is only suitable for small file uploads.
Django File Upload Instance