2

I am sending an uploaded file from the html view to the controller using ajax but the file is received as null in the controller.

I tried using FormData but nothing happens or maybe I am not using it right, when I sent the file using html.BeginForm() it was read correctly in the controller but I don't want to use forms because it opens another page after submitting

Below is my controller

public void Upload_SCN_CA_File(FormCollection formCollection)
{
    if (Request != null)
    {
        HttpPostedFileBase file = Request.Files["UploadedFile"];
        if ((file != null) && (file.ContentLength > 0) && !string.IsNullOrEmpty(file.FileName)) 
        {
            string fileName = file.FileName;
            Debug.WriteLine(fileName);
            string fileContentType = file.ContentType;
            byte[] fileBytes = new byte[file.ContentLength];
            var data = file.InputStream.Read(fileBytes, 0, Convert.ToInt32(file.ContentLength));
        }
    }
}

Below is the JQuery ajax call

$("#upload").on("click",function () {
    $.ajax({
        type: "POST",
        url: "/Order/Upload_SCN_CA_File",
        data: {
            enctype: 'multipart/form-data'
        },
        success: function (response) {
            if (response.result == false) {
                swal("Error", response.message, "error");
            }
            else {
                swal("Success", response.message, "success");
            }
        }
    });
});

Below is my html view

<form>
    <div class="row">
        <div class="col">
            <input name="UploadedFile" id="upfile" type="file" />
        </div>
    </div>
    <div class="row">
        <div class="col">
            <div class="btn btn-primary rounded" id="upload" style="margin:8px">Upload</div><br>
        </div>
    </div>
</form>

I expect the file to be sent correctly to the controller so I can read it correctly but it is received as null

andyb952
  • 1,931
  • 11
  • 25
Marina
  • 55
  • 6
  • `data: { enctype: 'multipart/form-data' },` - you don't appear to have included the file in your POST – freedomn-m Aug 20 '19 at 10:44
  • Possible duplicate of [jQuery Ajax File Upload](https://stackoverflow.com/questions/2320069/jquery-ajax-file-upload) – freedomn-m Aug 20 '19 at 10:46

2 Answers2

0

You must pass the form's content in the request using FormData API. You can collect it for example like this in the click handler

const form = $(this).closest('form').get(0)
const data = new FormData(form)

Then pass the following to the ajax call

data: data,
processData: false,
contentType: false

instead of

data: {
    enctype: 'multipart/form-data'
},

processData: false makes jquery pass the FormData instance unmodified to the XHR, which is required for the file upload to work. contentType: false will make the browser set multipart/form-data content type automatically.

FormData doest now work in older browsers, IE<10 specifically.

Rafał Rutkowski
  • 1,419
  • 10
  • 11
  • Thank you it worked but I got the same earlier problem, after the file is uploaded and read in the controller and the response is returned to the ajax in the view, the partial view disappears and the parent view is reloaded, do you have any solution? – Marina Aug 21 '19 at 11:23
  • You have to describe this problem with more details in a new question. You didn't mention any partial or parent views in this thread. Here we handle a click on a div, where we just send an AJAX request. It's not possible that this alone would cause some view to disappear or some view to reload. – Rafał Rutkowski Aug 21 '19 at 16:08
0

You may pass data something like in bellow code.

   $("#form0").submit(function (event) {
        var dataString;
        event.preventDefault();
        event.stopImmediatePropagation();
        var action = $("#form0").attr("action");
        if ($("#form0").attr("enctype") == "multipart/form-data") {
            dataString = new FormData($("#form0").get(0));
            contentType = false;
            processData = false;
        } else {
            // regular form, do your own thing if you need it
        }
        $.ajax({
            type: "POST",
            url: action,
            data: dataString,
            dataType: "json",
            contentType: contentType,
            processData: processData,
            success: function (data) {

            },
            error: function (jqXHR, textStatus, errorThrown) {

            }
        });
    });
vaibhav shah
  • 4,939
  • 19
  • 58
  • 96