0

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)   
mary
  • 57
  • 9
  • Can someone help ? Really stuck with this issue. – mary May 18 '21 at 03:44
  • Please post a screenshot and log of the postman request with the request and response body. – eshaan7 May 20 '21 at 15:24
  • 1
    Have you defined `UPLOAD_FOLDER` ? Please see: https://flask.palletsprojects.com/en/latest/patterns/fileuploads/#a-gentle-introduction – eshaan7 May 20 '21 at 15:25
  • Thank u so much. i have resolved the issue by creating a folder and saving the file before uploading it. As of now, i am passing the attribute (upload file) in body as form-data, can this be passed as raw json? – mary May 24 '21 at 02:41

1 Answers1

0

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)
eshaan7
  • 968
  • 2
  • 9
  • 17