Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Using python script to upload a file to django server localhost

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading