简体   繁体   中英

Check uploaded file is a image or not using asp.net web api

I'd like to check the uploaded file is an image or not using asp.net web api. I send a JSON string object from client side to web API. I can read the data of the uploaded file from server side, it's like " \\JFIF\\\\\H\H\\ "

Javascript code like this:

       var file = document.getElementById("UploadFile").files[0];

        if (file) {

            var fileReader = new FileReader();

            fileReader.readAsText(file, "UTF-8");

            fileReader.onload = function (evt) {

                $scope.BookingForm.Extension.FileContent = fileReader.result;

                $scope.BookingForm.Extension.FileName = file.name;
                $scope.BookingForm.Extension.FileSize = file.size;

fileReader.result is data of file. And here is ajax code to post data to web api.

    var fromdata = JSON.stringify($scope.BookingForm);
    var requestUrl = "/webapp/api/onlineform/PostOnlineForm"
    return $http({
        method: 'POST',
        url: requestUrl,
        data: fromdata,
        headers: {
            "Content-Type": "application/json; odata=verbose"
        }
    });

And here is the function from server side:

public async Task<IHttpActionResult> PostOnlineForm(OnlineForm formData)
        {
            Newtonsoft.Json.Linq.JObject extensionObj = Newtonsoft.Json.Linq.JObject.Parse(formData.Extensions);
            var dataOfFile = extensionObj["FileContent"].ToString();

            // code here

        } 

with variable "dataOfFile" is the string data of an uploaded file. I'd like to check variable "dataOfFile" is an image or not. Thank you very much.

Check the file for a file signature (the following code IsImage() checks for BMP, GIF, PNG, TIFF, JPEG)

public static class Extensions
{
    public static bool IsImage(this byte[] fileBytes)
    {
        if (fileBytes.Length < 2)
        {
            return false;
        }

        var headers = new List<byte[]>
        {
            new byte[] { 0x42, 0x4D }, // BMP
            new byte[] { 0x47, 0x49, 0x46, 0x38, 0x37, 0x61 }, // GIF
            new byte[] { 0x47, 0x49, 0x46, 0x38, 0x39, 0x61 }, // GIF
            new byte[] { 0x89, 0x50, 0x4e, 0x47, 0x0D, 0x0A, 0x1A, 0x0A }, // PNG
            new byte[] { 0x49, 0x49, 0x2A, 0x00 }, // TIFF
            new byte[] { 0x4D, 0x4D, 0x00, 0x2A }, // TIFF
            new byte[] { 0xFF, 0xD8, 0xFF }, // JPEG
            new byte[] { 0xFF, 0xD9 }, // JPEG
        };

        return headers.Any(x => x.SequenceEqual(fileBytes.Take(x.Length)));
    }
}

Your server side function would become

public async Task<IHttpActionResult> PostOnlineForm(OnlineForm formData)
{
    Newtonsoft.Json.Linq.JObject extensionObj = Newtonsoft.Json.Linq.JObject.Parse(formData.Extensions);
    var dataOfFile = extensionObj["FileContent"].ToString();
    
    // get first 8 bytes        
    int length = Math.Min(8, Encoding.UTF8.GetByteCount(dataOfFile));
    byte[] fileBytes = Encoding.UTF8.GetBytes(dataOfFile, 0, length); 

    bool isImage = fileBytes.IsImage();
} 

By the way, posting file content in json body is not the best way to upload files. Consider File upload scenarios .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM