How to Upload Image Via WebApi

前端 未结 6 1027
忘了有多久
忘了有多久 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:05

    WebApi supports deserializing JSON array, so that you can receive bytes by declaring with byte[].

    The following example will show how to upload image:

    public class ImageModel
    {
        public string Name { get; set; }
        public byte[] Bytes { get; set; }
    }
    

    In your controller. Writing image to disk:

    private string WriteImage(byte[] arr)
    {
        var filename = $@"images\{DateTime.Now.Ticks}.";
    
        using (var im = Image.FromStream(new MemoryStream(arr)))
        {
            ImageFormat frmt;
            if (ImageFormat.Png.Equals(im.RawFormat))
            {
                filename += "png";
                frmt = ImageFormat.Png;
            }
            else
            {
                filename += "jpg";
                frmt = ImageFormat.Jpeg;
            }
            string path = HttpContext.Current.Server.MapPath("~/") + filename;
            im.Save(path, frmt);
        }
    
        return $@"http:\\{Request.RequestUri.Host}\{filename}";
    }
    

    HttpContext.Current.Server.MapPath("~/") will give the internal path of server running. Request.RequestUri.Host returns the hostname.

    public IHttpActionResult UploadImage(ImageModel model)
    {
        var imgUrl = WriteImage(model.Bytes);
    
        // Some code
    }
    

    To send image from browser

    In HTML:

    
    

    Upload method for AngularJS:

    $scope.upload = function () {
    
         var file = document.getElementById("imageFile").files[0];
         var r = new FileReader();
         r.onloadend = function (e) {
    
    
             var arr = Array.from(new Uint8Array(e.target.result));
    
             var uploadData = {
                 Name: "Name of Image",
                 Bytes: arr
             }
             console.log(uploadData);
    
             $http.post('api/Uploader/UploadImage', uploadData)
             .then(
             function (response) {
                 console.log(response);
             },
    
             function (reason) {
    
                 console.log(reason);
             })
         }
         r.readAsArrayBuffer(file);
     }
    

提交回复
热议问题