将文件从WPF应用程序上传到Web API
问题描述:
我正在尝试将文件(图像)从WPF应用程序上传到Web Api控制器.在控制器中,我将文件转换为位数组并将其保存在DB中.我使用以下代码将文件发送到Web api
I am trying to upload a file (image) from a WPF application to a Web Api controller. In the controller I convert the file into a bit array and save it in a DB. I used the following code for sending files to web api
var client = new WebClient();
client.UploadFile("URI", "POST", "filepath");
在我的Web API中,我正在检查传入的请求是否为MimemultipartContent
In my web api I am checking if the incoming request is MimemultipartContent
if (Request.Content.IsMimeMultipartContent())
这很好.但是,当我尝试发送数据缓冲区而不是文件时,我陷入了如何编写服务器端代码的麻烦.
This works fine. But when I try to send a data buffer instead of a file I am stuck how to write my server side code.
var bytes = File.ReadAllBytes('filepath');
client.UploadData("URI", "POST", bytes);
答
知道了.其实很简单.
var task = Request.Content.ReadAsByteArrayAsync();
var bytes = task.Result;
Image img = new Image();
img.Id = Guid.NewGuid();
img.ImageData = bytes;
db.Images.Add(img);
db.SaveChanges();