我想通过ASP.NET MVC Web API将图像从Windows Phone客户端上传到服务器,但我遇到了麻烦。
我的服务器有以下代码:
[System.Web.Mvc.HttpPost]
public HttpResponseMessage UploadProfileImage([FromUri]int userId)
{
var task = this.Request.Content.ReadAsStreamAsync();
task.Wait();
Stream requestStream = task.Result;
var user = _context.Users.Where(x => x.UserId == userId).FirstOrDefault();
var res = System.IO.Path.GetDirectoryName(user.ProfileImagePath);
res = System.IO.Path.Combine(res, string.Format("ProfileImage{0}.jpg", user.UserName));
string filePath = System.Web.Hosting.HostingEnvironment.MapPath(res);
try
{
FileStream fs = System.IO.File.OpenWrite(filePath);
requestStream.CopyTo(fs);
fs.Close();
user.ProfileImagePath = res;
_context.Entry(user).State = EntityState.Modified;
_context.SaveChanges();
}
catch (Exception)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
HttpResponseMessage response = new HttpResponseMessage();
response.StatusCode = HttpStatusCode.Created;
return response;
}
在WP客户端中,我尝试使用此方法上传图像:
public void UpdateProfileImage(byte[] image)
{
string serviceUri = string.Format("http://localhost:4879/api/Application/UploadProfileImage?userId={0}", StaticDataManager.CurrentUserId);
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(serviceUri);
request.Headers["userId"] = StaticDataManager.CurrentUserId.ToString();
request.Method = "POST";
string message = "";
request.BeginGetRequestStream(result =>
{
Stream requestStream = request.EndGetRequestStream(result);
requestStream.Write(image, 0, image.Length);
request.BeginGetResponse(result2 =>
{
try
{
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(result2);
if (response.StatusCode == HttpStatusCode.Created)
{
message = "Its working";
}
else
{
message = "Something goes wrong";
}
}
catch(Exception ex)
{
message = ex.Message;
}
}, null);
}, null);
}
但是当我尝试上传图片时,我得到了以下异常: