In recent years, web applications have become increasingly popular, and many of them require file upload capabilities. In the Django framework, it is not difficult to implement the function of uploading files, but in actual development, we also need to process the uploaded files. Other operations include changing file names, limiting file sizes, and other issues. This article will share some file upload techniques in the Django framework.
1. Configuration file upload items
In the Django project, to configure file upload, you need to configure it in the settings.py file. Below we introduce several important configuration items.
File upload path
In settings.py, we can define the path to store uploaded files, as follows:
MEDIA_ROOT = os.path.join(BASE_DIR, 'uploads')
In this configuration item, we define The root directory for storing uploaded files is uploads, and the path of the media file is calculated relative to the directory where the settings.py file is located. We can also add corresponding URL rules in the urls.py of the Django project so that users can get uploaded files by accessing the URL.
Supported file formats
File format control is a very important content. We can specify the format of uploaded files through the following configuration items.
ALLOWED_FILE_TYPES = ['jpg', 'jpeg', 'png', 'gif', 'pdf']
Note that we must convert all file formats to lowercase letters.
File size limit
The Django framework limits the size of all files to no more than 2.5MB by default. If we need to modify this limit value, we can modify it in the settings.py configuration item.
MAX_UPLOAD_SIZE = 10485760 # 10MB
In this configuration, we limit the maximum upload file size to 10MB.
2. File upload
We can upload files through Django form components. The following is a simple file upload form example:
<form method="POST" enctype="multipart/form-data"> {% csrf_token %} <input type="file" name="document" accept=".pdf"> <input type="submit" value="Submit"> </form>
Note that the enctype attribute must be multipart/form-data to support file upload.
In the view function, we can use the request.FILES.get() method to get the uploaded file. This method returns a file object. Here is a simple example:
def upload(request): if request.method == 'POST': file = request.FILES.get('document') if file: handle_uploaded_file(file) messages.success(request, '上传成功') return redirect('home') else: messages.error(request, '上传失败') return redirect('upload') else: return render(request, 'upload.html')
In this example, we first get the uploaded file object, and then call the handle_uploaded_file() function to save it to the specified path. In the absence of uploaded files, we can prompt error messages to users through the messages module.
3. File naming
In order to better manage the files uploaded to the server, we recommend naming the uploaded files with a unique file name that contains a timestamp. Here is a simple example:
def handle_uploaded_file(file): date = datetime.now().strftime("%Y%m%d%H%M%S") filename = f"{date}_{file.name}" path = os.path.join(MEDIA_ROOT, filename) with open(path, 'wb+') as destination: for chunk in file.chunks(): destination.write(chunk)
First, we use the datetime module to get the current date and time and convert it to string format. We then combine this timestamp with the original filename to generate a new filename. Finally, we combine the new filename with the path to the uploaded file and write the uploaded file contents to the file using the file object's chunks() method.
4. File size
In order to prevent server problems, we need to limit the size of uploaded files. Below is a simple file size check function:
def check_file_size(file): if file.size > MAX_UPLOAD_SIZE: raise ValidationError(f'上传文件大小最大为 {MAX_UPLOAD_SIZE / 1048576} MB')
In this function, we check if the size of the uploaded file exceeds the maximum upload size. If it exceeds, we throw a ValidationError exception and prompt the user. Handle this exception in the view function:
def upload(request): if request.method == 'POST': file = request.FILES.get('document') if file: try: check_file_size(file) except ValidationError as e: messages.error(request, e) return redirect('upload') else: handle_uploaded_file(file) messages.success(request, '上传成功') return redirect('home') else: messages.error(request, '上传失败') return redirect('upload') else: return render(request, 'upload.html')
In this way, we can have better control over the size of the uploaded file.
Summary:
The above is the detailed content of File upload skills in Django framework. For more information, please follow other related articles on the PHP Chinese website!