arctic.queenolina
arctic.queenolina

Reputation: 163

POST method adds a header to an xlsx file which corrupts it

I'm trying to send an xlsx file using Python requests library. My request looks like this:

import requests

url_attachment = "http://127.0.0.1:5000/api/attachment"
payload={}
files=[('file',(filename, open(filename,'rb'),'application/octet-stream'))
]
headers = {}
requests.request("POST", url_attachment, headers=headers, data=payload, files=files)

and my mock server looks like this:

import flask
from flask import request

app = flask.Flask(__name__)
app.config["DEBUG"] = True


@app.route('/', methods=['GET'])
def home():
    return "<h1>Hello World</h1>"

@app.route('/api/attachment', methods=['POST'])
def get_file():
    data = request.files['file']
    data.save('the-file.xlsx')

    return "ok"



app.run()

The mock server works fine, and the file gets sent correctly. However, when I call the actual API (that I have no access to), the file gets corrupted. The person who owns the API sent me the corrupted file, and after inspection I can see that the content got wrapped in this:

-------------------------------28947758029299
Content-Disposition: form-data; name="the-file.xlsx"; filename="the-file.xlsx"
Content-Type: application/octet-stream

//content

-------------------------------28947758029299--

Does someone have an idea why this is happening? What can I change in my function to stop this from happening? I have also tried changing the Content-Type to application/vnd.openxmlformatsofficedocument.spreadsheetml.sheet but apparently this results in the same problem.

Upvotes: 0

Views: 493

Answers (1)

arctic.queenolina
arctic.queenolina

Reputation: 163

This has been resolved now. If anyone comes across a similar issue in the future, the cause was the receiving method in the API considering content as 'multi-part form data'.

Upvotes: 1

Related Questions