pallets/flask

When using Flask to receive multiple files, an extra ‘0D’ appears at the end of some images

simpia opened this issue · 1 comments

When using Flask to receive multiple image files, occasionally an extra "0D" appears at the end of the image. The original data is saved, and the end of this image is normal "FFD90D0A". Packet capture tools also show a normal ending. If this request is sent repeatedly, the same error will continue to occur, and the saved image cannot be resent to reproduce the issue.

Below is the main code for sending and receiving. This code cannot be run directly because it needs to read some data.

files={}
files[i]=("name", data[i], 'image/jpeg')
response = requests.post(
            "http://192.168.1.50:8006/test",
            files = files,
        )
import flask

app = flask.Flask(__name__)

@app.before_request
def before_request():
    path=flask.request.path
    data=flask.request.get_data(cache=True, as_text=False)
    flask.request.data1=data

@app.route('/test', methods = ['POST'])
def testfile():
    data=flask.request.data1
    files=flask.request.files
    files=[(i,files[i]) for i in files]
    for i in range(len(files)):
        with open(f"test/{i}.jpg","wb") as f:
            files[i][1].seek(0, os.SEEK_END)
            file_size = files[i][1].tell()
            files[i][1].seek(0)
            f.write(files[i][1].read(file_size))
    return flask.jsonify({"code":0})

if __name__ == '__main__':
    app.run(host="0.0.0.0",port=8006)

I have analyzed the raw data and source code, and used packet capture tools to view the received data, all of which are normal. I suspect there is a problem with the parsing, but the flask source code shows that the parsing will remove "\r\n", why would there still be errors?

The probability of this issue occurring is very small, making it difficult to reproduce. However, when it does occur, the same error will occur.

Upgrade to the latest version of Werkzeug.

Duplicate of pallets/werkzeug#2761