2

I am developing API using Flask-restplus. One of the endpoints handles audio file uploads which can be either mp3 or wav format. According to PUT request to upload a file not working in Flask, file uploaded by put is in either request.data or request.stream. So this is what I did:

@ns.route('/upload')
class AudioUpload(Resource):
    def put(self):
        now = datetime.now()
        filename = now.strftime("%Y%m%d_%H%M%S") + ".mp3"
        cwd = os.getcwd()
        filepath = os.path.join(cwd, filename)
        with open(filepath, 'wb') as f:
            f.write(request.stream.read())
        return filepath

I am saving the file as mp3. However sometime the file comes in as wav. Is there a way to get the original file name from put request in the similar way as post request:

file = request.files['file']
filename = file.filename
ddd
  • 3,567
  • 8
  • 49
  • 106
  • Is there a reason you are using a PUT request instead of a POST request? If you wish to override this audio file value then I guess PUT requests make sense, but POST vs PUT is up to you discretion so you can choose to use a POST instead of a PUT – James Russo Apr 30 '18 at 21:02
  • @JamesRusso Our client, the consumer of the API insists using PUT request instead of POST which I don't quite understand – ddd Apr 30 '18 at 21:05
  • The filename is not part of the file. To upload a file and also include the name, use multipart form-data content in the http put request. If you transmit just the raw data content of the file, the filename is not included. – Håken Lid Apr 30 '18 at 21:11
  • 1
    Using PUT would typically mean that the request should go to a unique url. For example `PUT /upload/good-vibrations.mp3`. In that case, you could simply get the filename from the url route. – Håken Lid Apr 30 '18 at 21:13
  • 2
    The best way to figure out the correct file type is by inspecting the file contents. It's quite common that filename extensions are missing or incorrect anyway. You can use the linux `file` command or `python-magic` to distinguish a wav file from a mp3 file. https://github.com/ahupp/python-magic – Håken Lid Apr 30 '18 at 21:19
  • 1
    @HåkenLid I've never dealt with PUT before. Can you be more specific for how to get file name from the request url? – ddd May 04 '18 at 14:06
  • The convention is that methods put, get, delete and patch go to an endpoint unique to one resource. For example `/users/4` while post are done to a single endpoint. `/users/` or maybe `/users/create/`. So you could create an API where files are uploaded to endpoints where the client decides the filename part of the URL. I'm not familiar with flask-restful, so I can't point you to examples or docs, but I'm sure this is possible with Flask if you want to do it. However I believe using a single URL with multipart form-data is more conventional. – Håken Lid May 04 '18 at 14:58

0 Answers0