如何通过WebApi上传图像 [英] How to Upload Image Via WebApi

查看:397
本文介绍了如何通过WebApi上传图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何通过 ASP.NET Web API 上传图像文件?
我在文件模式下有一个输入标签,它已发布到API,如何将其保存到服务器文件夹?
我尝试了这段代码,但是没有用:

How I can upload Image File via ASP.NET Web API?
I have an input tag in File mode and it posted to API, how I can save it to server folder?
I tried this code but it doesn't worked:

private void UploadWholeFile(HttpRequestBase request)
{
   for (int i = 0; i < request.Files.Count; i++)
   {
      var file = request.Files[i];

      var ext = new FileInfo(file.FileName).Extension;
      var fullPath = Path.Combine(StorageRoot, Path.GetFileName(Guid.NewGuid() + ext));

      file.SaveAs(fullPath);
   }
}

推荐答案

在这里,我已经描述了在网络api中上传图像的整个过程

[Route("user/PostUserImage")]
public async Task<HttpResponseMessage> PostUserImage()
{
    Dictionary<string, object> dict = new Dictionary<string, object>();
    try
    {

        var httpRequest = HttpContext.Current.Request;

        foreach (string file in httpRequest.Files)
        {
            HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created);

            var postedFile = httpRequest.Files[file];
            if (postedFile != null && postedFile.ContentLength > 0)
            {

                int MaxContentLength = 1024 * 1024 * 1; //Size = 1 MB

                IList<string> AllowedFileExtensions = new List<string> { ".jpg", ".gif", ".png" };
                var ext = postedFile.FileName.Substring(postedFile.FileName.LastIndexOf('.'));
                var extension = ext.ToLower();
                if (!AllowedFileExtensions.Contains(extension))
                {

                    var message = string.Format("Please Upload image of type .jpg,.gif,.png.");

                    dict.Add("error", message);
                    return Request.CreateResponse(HttpStatusCode.BadRequest, dict);
                }
                else if (postedFile.ContentLength > MaxContentLength)
                {

                    var message = string.Format("Please Upload a file upto 1 mb.");

                    dict.Add("error", message);
                    return Request.CreateResponse(HttpStatusCode.BadRequest, dict);
                }
                else
                {

                    YourModelProperty.imageurl = userInfo.email_id + extension;
                    //  where you want to attach your imageurl

                    //if needed write the code to update the table

                    var filePath = HttpContext.Current.Server.MapPath("~/Userimage/" + userInfo.email_id + extension);
                    //Userimage myfolder name where i want to save my image
                    postedFile.SaveAs(filePath);

                }
            }

            var message1 = string.Format("Image Updated Successfully.");
            return Request.CreateErrorResponse(HttpStatusCode.Created, message1); ;
        }
        var res = string.Format("Please Upload a image.");
        dict.Add("error", res);
        return Request.CreateResponse(HttpStatusCode.NotFound, dict);
    }
    catch (Exception ex)
    {
        var res = string.Format("some Message");
        dict.Add("error", res);
        return Request.CreateResponse(HttpStatusCode.NotFound, dict);
    }
}

这篇关于如何通过WebApi上传图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆