尝试将文件从UWP应用上传到Flask Restful Web API,失败

时间:2019-01-27 23:46:37

标签: c# flask uwp

我正在尝试使用C#构建UWP应用程序。我还使用其他设备(例如树莓派)上的flask构建了一个宁静的Web api。但是,当我尝试通过api将UWP应用中的图像上传到树莓派时,树莓派没有收到文件,而请求似乎成功了。

因此,在树莓派上运行Web API,然后在Windows 10上运行uwp应用程序后,我得到了以下返回信息:“无文件”。

这是我的UWP应用程序的代码

public async void Upload_FileAsync(string WebServiceURL, string 
FilePathToUpload){
    IStorageFile storageFile = await 
    StorageFile.GetFileFromPathAsync(FilePathToUpload);

    IRandomAccessStream stream = await 
    storageFile.OpenAsync(FileAccessMode.Read);
    HttpStreamContent streamfile = new HttpStreamContent(stream);
    HttpMultipartFormDataContent httpContents = new 
                      HttpMultipartFormDataContent();

    httpContents.Headers.ContentType.MediaType = "multipart/form-data";
    httpContents.Add(streamfile, "file");

    var client = new HttpClient();
    HttpResponseMessage result = await client.PostAsync(
                       new Uri(WebServiceURL), httpContents);
    string stringReadResult = await result.Content.ReadAsStringAsync();
    textBox.Text = stringReadResult;
}

这就是我调用函数的方式

Upload_FileAsync("http://192.168.0.111:5000/upload", 
             "c:\\pictures\\testImage3.jpg");

这是rest api的代码

from flask import Flask
from flask_restful import Resource, Api, reqparse
import werkzeug, os

app = Flask(__name__)
api = Api(app)
UPLOAD_FOLDER = 'static/img'
parser = reqparse.RequestParser()
parser.add_argument('file',
    type=werkzeug.datastructures.FileStorage,
    location='files')

class PhotoUpload(Resource):
    def post(self):
        data = parser.parse_args()
        if data['file'] == None:
            return "no file"
        photo = data['file']

        if photo:
            filename = 'received.png'
            photo.save(os.path.join(UPLOAD_FOLDER, filename))
            return "file uploaded"

api.add_resource(PhotoUpload, '/upload')

if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0')

我期望的是:通过api成功将图像上传到raspberry pi并将其存储在raspberry pi上。但是实际输出是“没有文件”。

在树莓派上的打印输出是这样的:

[27/Jan/2019 17:18:02] "POST /upload HTTP/1.1" 200 -

所以请求看起来不错,但文件不在请求中。

1 个答案:

答案 0 :(得分:0)

我发现了问题。 调用此函数时,我忘了解析文件名:

httpContents.Add(streamfile, "file");

因此,正确的做法是:

httpContents.Add(streamfile, "file", Path.GetFileName(FilePathToUpload));

现在可以使用了!