How to Upload Image Via WebApi

前端 未结 6 1045
忘了有多久
忘了有多久 2020-12-02 12:53

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 th

6条回答
  •  误落风尘
    2020-12-02 13:18

    You Can Use This Sample To Upload Image In Web Api.

    First create ImageWriterHelper to check the file format

      public class ImageWriterHelper
            {
                public enum ImageFormat
                {
                    Bmp,
                    Jpeg,
                    Gif,
                    Tiff,
                    Png,
                    Unknown
                }
    
            public static ImageFormat GetImageFormat(byte[] bytes)
            {
                var bmp = Encoding.ASCII.GetBytes("BM");
                var gif = Encoding.ASCII.GetBytes("GIF");
                var png = new byte[] { 137, 80, 78, 71 };
                var tiff = new byte[] { 73, 73, 42 };
                var tiff2 = new byte[] { 77, 77, 42 };
                var jpeg = new byte[] { 255, 216, 255, 224 };
                var jpeg2 = new byte[] { 255, 216, 255, 225 };
    
                if (bmp.SequenceEqual(bytes.Take(bmp.Length)))
                    return ImageFormat.Bmp;
    
                if (gif.SequenceEqual(bytes.Take(gif.Length)))
                    return ImageFormat.Gif;
    
                if (png.SequenceEqual(bytes.Take(png.Length)))
                    return ImageFormat.Png;
    
                if (tiff.SequenceEqual(bytes.Take(tiff.Length)))
                    return ImageFormat.Tiff;
    
                if (tiff2.SequenceEqual(bytes.Take(tiff2.Length)))
                    return ImageFormat.Tiff;
    
                if (jpeg.SequenceEqual(bytes.Take(jpeg.Length)))
                    return ImageFormat.Jpeg;
    
                if (jpeg2.SequenceEqual(bytes.Take(jpeg2.Length)))
                    return ImageFormat.Jpeg;
    
                return ImageFormat.Unknown;
            }
            }
    

    Then you should create class for saving image

      public class AddCandidateProfilePictureCommand:     
                                           IAddCandidateProfilePictureCommand
           {
            public AddCandidateProfilePictureResponse Execute(HttpPostedFile 
           postedFile)
            {
                byte[] fileBytes;
    
                using (var memoryStream = new MemoryStream())
                {
                    postedFile.InputStream.CopyTo(memoryStream);
                    fileBytes = memoryStream.ToArray();
                }
    
                if (ImageWriterHelper.GetImageFormat(fileBytes) == 
                    ImageWriterHelper.ImageFormat.Unknown)
                    throw new BadImageFormatException();
    
                var extension = Path.GetExtension(postedFile.FileName);
                var tempCandidateImageName = Guid.NewGuid();
                var fileName = $"{tempCandidateImageName}{extension}";
                var fileUrl =              
        WebConfigurationManager.AppSettings["CandidateProfilePictureAddress"];
    
                var filePath = Path.Combine(fileUrl, fileName);
    
                if (!Directory.Exists(fileUrl))
                    Directory.CreateDirectory(fileUrl);
    
                postedFile.SaveAfterResizeImage(filePath, extension);
    
                return new AddCandidateProfilePictureResponse { 
                          TempCandidateImageName = fileName };
            }
            }
    

    Next create class ImageResizeHelper to resize the image

     public static class ImageResizeHelper
            {
                public static void SaveAfterResizeImage( this HttpPostedFile 
                                   postedFile,string filePath, string extension)
                {
                    postedFile.SaveAs(filePath);
    
                    var resizeSetting = new ResizeSettings
                    {
                        Width = 500,
                        Height = 500,
                        Format = extension
                    };
    
                    ImageBuilder.Current.Build(filePath,ilePath,resizeSetting);
                }
            }
    

    At the end create action In Controller

      [HttpPost]
            public IHttpActionResult AddCandidateProfilePicture()
            {
                var request = HttpContext.Current.Request;
                const int maxContentLength = 512 * 512 * 1;
    
                if (request.ContentLength > maxContentLength || 
                    request.Files.Count == 0)
                    return BadRequest();
    
                var pictureFile = request.Files[0];
    
                var result = 
    AddCandidateProfilePictureCommand.Execute(pictureFile);
    
                return Ok(result);
            }
    

    I Used constructor injection for creating an instance of classes

    please see this link: Uploading Image To Server Using Web API 2.0

提交回复
热议问题