0

I'm aiming to send fileform with images and additional information like height and width. I can't figure out how to add some custom props to file form object.

 $("#saveImg").on('click', function () {
        var formData = new FormData(),
            allFiles = [];
    $('input[name=fileUpload]').each(function (index) {
        if (inputFileValidation(this)) {
            (function (files) {
                if (files.length != 0) { allFiles.push(files[0]); }
            })(this.files)
        }
    });

    for (var i = 0; i != allFiles.length; i++) {
        var img = new Image()
        img.src = window.URL.createObjectURL(allFiles[i]);
        $(img).on('load', function () {
            formData.append("files_h", img.naturalHeight);
            formData.append("files_w", img.naturalWidth);
            formData.append("files", allFiles[i]);
            window.URL.revokeObjectURL(allFiles[i]);
        });
    }

    $.ajax({
        url: '@Url.Action("Upload", "Image")',
        data: formData,
        processData: false,
        contentType: false,
        type: "POST",
        success: function () {}
        errors: function () {}
    });
});


[HttpPost]
public async Task<IActionResult> Upload (IList<IFormFile> files)
{
    //do something ;
}

I also tried:

[HttpPost]
public async Task<IActionResult> Upload (IList<IFormFile> files, IList<IFormFile> files_h, IList<IFormFile> files_w)
{
    //do something ;
}

Maybe you have another idea how to send image with additional data? I tried to convert file form and additional info to JSON by that didn't work.

Edit Thank you all for your suggestion, they are really important to me because I will definitely use them in the future.

However, in this project I have already given up using the file reader due to its asynchrony and having fun with promise. The aim is simple and less javascript and more c#

I apologize for misleading you in the title javascript andjquery - and I mark the answer related to c #. I did this because this answer is related to my next task because the CoreCompat.System.Drawing library is undoubtedly still useful for editing photos in the future.

Thanks!!

szkut
  • 353
  • 2
  • 22
  • 1
    https://stackoverflow.com/questions/31839449/how-to-upload-image-via-webapi – fuzzybear Nov 21 '18 at 21:30
  • all your suggestions require the use of `HttpContext.Current.Request.Files` - my controller doesn't know what it is. I'm using asp core mvc 2 and can't find the right `using`. **Edit:** more accurately - HttpContext doesn't have Current. `HttpContext` comes from `ControllerBase.HttpContext` – szkut Nov 21 '18 at 22:34
  • 1
    you need to register httpcontext and pass it as dependecy – fuzzybear Nov 21 '18 at 23:48
  • 1
    see https://stackoverflow.com/questions/31243068/access-the-current-httpcontext-in-asp-net-core – fuzzybear Nov 21 '18 at 23:51

2 Answers2

1

This is one approach; taken from there:

$('#btnUpload').click(function () {  

    // Checking whether FormData is available in browser  
    if (window.FormData !== undefined) {  

        var fileUpload = $("#FileUpload1").get(0);  
        var files = fileUpload.files;  

        // Create FormData object  
        var fileData = new FormData();  

        // Looping over all files and add it to FormData object  
        for (var i = 0; i < files.length; i++) {  
            fileData.append(files[i].name, files[i]);  
        }  

        // Adding one more key to FormData object  
        fileData.append('username', ‘Manas’);  

        $.ajax({  
            url: '/Home/UploadFiles',  
            type: "POST",  
            contentType: false, // Not to set any content header  
            processData: false, // Not to process data  
            data: fileData,  
            success: function (result) {  
                alert(result);  
            },  
            error: function (err) {  
                alert(err.statusText);  
            }  
        });  
    } else {  
        alert("FormData is not supported.");  
    }  
});  

Another approach is to use the FileReader class to read the uploaded file, convert it to a base 64 string. Then you can send the base 64 string to the server.

Brian Mains
  • 50,520
  • 35
  • 148
  • 257
1

If you want to get the Width and Height properties while uploading images in ASP.NET Core. I suggest you to install this package: CoreCompat.System.Drawing

Install-Package CoreCompat.System.Drawing -Version 1.0.0-beta006


In the server, after saving your files to the specific path. You could use System.Drawing.Image class to get the Width and Height properties:

using (var image = System.Drawing.Image.FromFile(filePath))
{
    int width = image.Width;
    int height = image.Height;
}

You don't have to add files_h and files_w properties to your client model before sending to server.


And then, by using this way, I've edited your js code to:

 $("#saveImg").on('click', function () {
    var formData = new FormData();

    for (var input of Array.from($('input[name=fileUpload]')))
    {
        if (inputFileValidation(input) && input.files.length) {
            formData.append('files', input.files[0]);
        }
    }

    $.ajax({
        url: '@Url.Action("Upload", "Image")',
        data: formData,
        processData: false,
        contentType: false,
        type: "POST",
        success: function () {}
        errors: function () {}
    });
});
Tân
  • 1
  • 15
  • 56
  • 102