I am sending a put request to upload a file using python requests library:
f = open(fname, "rb")
files = {"file": f.read()}
response = requests.put(url, auth=auth, files=files, timeout=timeout)
However in the server side I do get my file with the following header
Content-Disposition: form-data; name="file"; filename="file"
Is there a way I can get rid of this?
Related
My request body looks as shown below. Am trying to get filename, uploadedBy and csv file and save to my local machine as csv.
------WebKitFormBoundarypm79CqkInUFFrKPU
Content-Disposition: form-data; name="fileName"
sample.csv
------WebKitFormBoundarypm79CqkInUFFrKPU
Content-Disposition: form-data; name="uploadedBy"
someEmail#email.com
------WebKitFormBoundarypm79CqkInUFFrKPU
Content-Disposition: form-data; name="file"; filename="sample.csv"
Content-Type: text/csv
------WebKitFormBoundarypm79CqkInUFFrKPU--
I am trying to trigger an external api from postman by passing the uploadFile in the body as form-data. Below code throws me an error as 'FileNotFoundError: [Errno 2] No such file or directory:'
Note: In postman, uploadFile takes file from my local desktop as input. have also modified the postman settings to allow access for files apart from working directory
Any help would be highly appreciable.
Below is the Code:
#app.route('/upload', methods=['POST'])
#auth.login_required
def post_upload():
payload = {
'table_name': 'incident', 'table_sys_id': request.form['table_sys_id']
}
files = {'file': (request.files['uploadFile'], open(request.files['uploadFile'].filename,
'rb'),'image/jpg', {'Expires': '0'})}
response = requests.post(url, headers=headers, files=files, data=payload)
return jsonify("Success- Attachment uploaded successfully ", 200)
Below code throws me an error as 'FileNotFoundError: [Errno 2] No such file or directory:
Have you defined UPLOAD_FOLDER ? Please see: https://flask.palletsprojects.com/en/latest/patterns/fileuploads/#a-gentle-introduction
i am passing the attribute (upload file) in body as form-data, can this be passed as raw json
You cannot upload files with JSON. But one hacky way to achieve this is to base64 (useful reference) encode the file before sending it. This way you do not upload the file instead you send the file content encoded in base64 format.
Server side:
import base64
file_content = base64.b64decode(request.data['file_buffer_b64'])
Client side:
-> Javascript:
const response = await axios.post(uri, {file_buffer_b64: window.btoa(file)})
-> Python:
import base64
with open(request.data['uploadFile'], "rb") as myfile:
encoded_string = base64.b64encode(myfile.read())
payload = {"file_buffer_b64": encoded_string}
response = requests.post(url, data=payload)
I have to post a file using Multipart upload to a company-internal REST service. The endpoint needs the file as property "file" and it needs an additional property "DestinationPath". Here is what I do:
url = r"http://<Internal IP>/upload"
files = {
"DestinationPath": "/some/where/foo.txt",
"file": open("test.txt", "rb")
}
response = requests.post(url, files=files)
The server complains that it can't get the "DestinationPath". Full error message I receive is:
{'errors': {'DestinationPath': ['The DestinationPath field is required.']},
'status': 400,
'title': 'One or more validation errors occurred.',
'traceId': '00-1993fbc53ab2ee418b683915dd7a440a-2338bd9cf34d414a-00',
'type': 'https://tools.ietf.org/html/rfc7231#section-6.5.1'}
The file upload works in curl, thus it must be python specific.
You might want to try using the data argument instead of files.
response = requests.post(url, data=files)
Thanks to #etemple1 I found the solution to my question:
url = r"http://<Internal IP>/upload"
data = {
"DestinationPath": "/some/where/foo.txt",
}
with open("test.txt", "rb") as content:
files = {
"file": content.read(),
}
response = requests.post(url, data=data, files=files)
The data for the multipart upload needed to be divided between "data" and "files". They are later combined in the body of the http post by the requests library.
I'm trying to handle a request that contains a csv file in the body . Exist any library in python3 that extract or parse the http request and grab the csv file. I'm a beginner in python.
My request
file = {'file': open('../file/10.csv', 'rb')}
response = requests.post('http://127.0.0.1:8080/function/preprocess', files=file)
print(response.content)
My handler
def handle(event, context):
return {
"statusCode": 200,
"body": event.body
}
Postman
---------------------------157082355573515401018537
Content-Disposition: form-data; name="file"; filename="10.csv"
Content-Type: text/csv
id,vendor_id,pickup_datetime,dropoff_datetime,passenger_count,pickup_longitude,pickup_latitude,dropoff_longitude,dropoff_latitude,store_and_fwd_flag,trip_duration
id2875421,2,2016-03-14 17:24:55,2016-03-14 17:32:30,1,-73.982154846191406,40.767936706542969,-73.964630126953125,40.765602111816406,N,455
----------------------------157082355573515401018537--
I'm trying to call an external ReST service.
retrofit_version = "2.9.0"
okhttp = "3.14.9"
This is the Retrofit interface as I define it:
#Multipart
#POST("orgs/{orgUuid}/patients/{patientId}/documents")
Call<DocUploadRes> uploadDocForPatient(#Header("Authorization") String authorization,
#Path("orgUuid") String orgUuid,
#Path("patientId") Integer patientId,
#Part("metadata") RequestBody metadata,
#Part MultipartBody.Part file);
My Client call is as follow:
RequestBody metadataBody = RequestBody.create(MediaType.parse("application/json"), content);
MultipartBody.Part filePart = MultipartBody.Part.createFormData("file","Safereport", RequestBody.create(MediaType.parse("application/pdf"), file.getBytes()));
Response<DocUploadRes> response = pccPatientRestApi.uploadDocForPatient(getBearerAuthHeader(pccAccessToken), pccOrgUuid, patientId, jsonPart, filePart).execute();
When I'm running this code with retrofit I'm getting Bad Request from the server with:
status":"400","title":"Bad Request.","detail":"File type is not supported"
But when I run the same service from postman it working successfully with the following http request sent:
POST /api/public/preview1/orgs/E58A8604-38F2-4098-879E-C6BCC6D01EB8/patients/372842/documents HTTP/1.1
Host: connect2.pointclickcare.com
Authorization: Bearer iy8OUOVa46oxaYRMVYlRApqDW00m:2Content-Type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW
----WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="file"; filename="/C:/Users/user/Desktop/RosieConnect-20-API-User-Manual-Ver-07172018.pdf"
Content-Type: application/pdf
(data)
----WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="metadata"
{"documentCategory":1,"documentName":"Safebeing Report","effectiveDate":"2020-05-26T08:03:49.895Z"}
----WebKitFormBoundary7MA4YWxkTrZu0gW
It seems to me that retrofit doesn't send the 'application/pdf' in the Content-Type header of the file #Part... how can it be fixed?
Any idea will be very much appreciated!
-- Update ---
It appears the the file extension is mandatory.
Problem solved by adding .pdf to the file name
MultipartBody.Part filePart = MultipartBody.Part.createFormData("file","report.pdf", RequestBody.create(MediaType.parse("application/pdf"), file.getBytes()));