Advertisements
I build an django rest framework that can help me to upload a file
in view.py
class FileResultViewSet(viewsets.ModelViewSet):
queryset = FileResult.objects.order_by('-timestamp')
serializer_class = FileResultSerializer
parser_classes = (MultiPartParser, FormParser)
def perform_create(self, serializer):
serializer.save()
The script work well without any error, and the file is stored in media folder
Then, I use an python script that can help me to upload file to django
import requests
import openpyxl
url = "http://localhost:8000/upload/"
headers = {'Content-Type': 'multipart/form-data'}
file_path = "H:/MEGA_H/Data/uploaded/Book1.xlsx"
'''
with open(file_path, 'rb') as f:
file = {'file': f}
response = requests.get(url, headers=headers, files=file)
'''
filename = "Book1.xlsx"
# Open the file and read its contents
with open(file_path, 'rb') as f:
file_contents = f.read()
# Create a dictionary to store the file information
#file_data = {'file': (filename, file_contents,result_file)}
file_data = {
"result_file": file_contents
}
# Make a POST request to the URL with the file information
response = requests.post(url, files=file_data)
# Check if the request was successful
if response.status_code == 201:
print("File successfully uploaded")
else:
print("Failed to upload file")
The code still works with an issue, after upload the file to media folder, the file doesnt include the file type, so it can not read. I have to change the name of the file , and typing file type ".xlsx"
The file name is only Book1, without Book1.xlsx
>Solution :
with open(file_path, 'rb') as f:
file_contents = f.read()
file_data = {
"result_file": file_contents
}
This is the wrong way to do it. The dict should contain the file object itself, not the file contents.
with open(file_path, 'rb') as f:
file_data = {"result_file": f}
response = requests.post(url, files=file_data)