从iOS上传Flask文件

时间:2015-08-27 21:34:33

标签: python ios flask

我正在尝试将我的iOS应用程序中的音频文件上传到我的烧瓶后端。 POST请求通过,但我收到错误消息“浏览器(或代理)发送了此服务器无法理解的请求。”

我正在查看烧瓶文档来做这件事,但我看不出他们做的那些不同。

@auth.route('/uploadfile', methods=['GET', 'POST'])
def upload_file():
    if request.method == 'POST':
        print('post request received')
        file = request.files['file']
        if file and allowed_file(file.filename):
            print('file name is valid and saving')
            filename = secure_filename(file.filename)
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
            return jsonify({'success': 1})
        else:
            print('file failed to save')
            return jsonify({'success': 2})


def allowed_file(filename):
    print('in allowed_file')
    return '.' in filename and \
        filename.rsplit('.', 1)[1] in app.config['AllOWED_EXTENSIONS']

//Config settings
UPLOAD_FOLDER = '/Users/Michael/Desktop/uploads'
ALLOWED_EXTENSIONS = set(['m4a'])

iOS端

func savePressed(){

    var stringVersion = recordingURL?.path
    let encodedSound = NSFileManager.defaultManager().contentsAtPath(stringVersion!)
    let encodedBase64Sound = encodedSound!.base64EncodedStringWithOptions(nil)
    let dict = ["file": encodedBase64Sound]        
    let urlString = "http://127.0.0.1:5000/auth/uploadfile"
    var request = NSMutableURLRequest(URL: NSURL(string: urlString)!)
    var session = NSURLSession.sharedSession()
    request.HTTPMethod = "Post"
    var err: NSError?
    request.HTTPBody = NSJSONSerialization.dataWithJSONObject(dict as NSDictionary, options: nil, error: &err)
    request.addValue("application/json", forHTTPHeaderField: "Content-Type")
    request.addValue("application/json", forHTTPHeaderField: "Accept")

    //Completion handler
    var task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in

1 个答案:

答案 0 :(得分:1)

您对baseF进行编码并将其发布到application/json类型的JSON对象中。只有在发出files类型请求时才会填充multipart/form-data

因此,没有名为" file"在request.files中,而是base64编码的字符串"文件"在request.json。当您尝试访问不存在的请求集合上的密钥时,Flask会引发错误。

您当前的方式有效,您仍然可以将字符串解码为二进制并保存,但您需要生成自己的文件名或单独发送。

from base64 import b64decode
b64_data = request.json['file']  # the base64 encoded string
bin_data = base64decode(b64_data)  # decode it into bytes

# perhaps send the filename as part of the JSON as well, or make one up locally
filename = secure_filename(request.json['filename'])

with open(filename, 'wb') as f:
    f.write(bin_data)  # write the decoded bytes

正确的解决方案是将帖子设为multipart/form-data,并将文件放在正文的文件部分中。我不知道如何在iOS中执行此操作,但绝对应该支持它。这是使用Python requests库的帖子的样子。如果您可以在iOS中获得相同的内容,那么您就不必更改Flask代码。

with open(recording, 'rb') as f:
    requests.post('http://127.0.0.1:5000/auth/uploadfile', files={'file': f})