异步上传asp mvc 5

时间:2016-06-09 23:56:56

标签: asp.net asp.net-mvc file-upload asp.net-mvc-5 internal-server-error

刚开始使用ASP.Net 4.5,我的API总是返回内部服务器错误。

上传API

public class UploadController : ApiController
{
    public async Task<HttpResponseMessage> PostFile()
    {  
        if (!Request.Content.IsMimeMultipartContent())
        {
            throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
        }

        string root = HttpContext.Current.Server.MapPath("~/App_Data/uploads/");
        var provider = new CustomMultipartFormDataStreamProvider(root);

        try
        {
            await Request.Content.ReadAsMultipartAsync(provider);

            return Request.CreateResponse(HttpStatusCode.OK);
        }
        catch (System.Exception e)
        {
            return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e);
        }
    }

}

我的控制器

    var message = new HttpRequestMessage();
    var content = new MultipartFormDataContent();
    message.Method = HttpMethod.Post;
    message.Content = content;
    message.RequestUri = new Uri("http://localhost:12345/api/upload/");

    var client = new HttpClient();
    client.SendAsync(message).ContinueWith(task =>
    {
            var result = task.Result.ReasonPhrase;
            if (task.Result.IsSuccessStatusCode)
            {
                    //do something
            }
    });

文件保存在位置(/ App_Data / uploads /),但为什么状态代码总是500?

请赐教。感谢

1 个答案:

答案 0 :(得分:0)

这是工作控制器的一部分:

[HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> Create(Product product, HttpPostedFileBase file)
    {
        if (!ModelState.IsValid)
            return PartialView("Create", product);
        if (file != null)
        {

            var fileName = Path.GetFileName(file.FileName);
            var guid = Guid.NewGuid().ToString();
            var path = Path.Combine(Server.MapPath("~/Content/Uploads/ProductImages"), guid + fileName);
            file.SaveAs(path);
            string fl = path.Substring(path.LastIndexOf("\\"));
            string[] split = fl.Split('\\');
            string newpath = split[1];
            string imagepath = "Content/Uploads/ProductImages/" + newpath;
            using (MemoryStream ms = new MemoryStream())
            {
                file.InputStream.CopyTo(ms);
                byte[] array = ms.GetBuffer();
            }
            var nId = Guid.NewGuid().ToString();
            // Save record to database
            product.Id = nId;
            product.State = 1;
            product.ImagePath = imagepath;
            product.CreatedAt = DateTime.Now;
            db.Products.Add(product);
            await db.SaveChangesAsync();
            TempData["message"] = "ProductCreated";

            //return RedirectToAction("Index", product);
        }
        // after successfully uploading redirect the user
        return Json(new { success = true });
    }