0

I have a view that accept a file like so:

<form method="post" id="myform" enctype="multipart/form-data"
      asp-controller="UploadFiles" asp-action="Index">
    <div class="form-group">
        <div class="col-md-10">
            <p>Seleziona un file ORI ed un file MOD.</p>
            <label for="fileOri">Seleziona ORI</label>
            <input id="fileOri" type="file" name="fileOri" multiple />
            <p></p>
            <label for="fileMod">Seleziona MOD</label>
            <input id="fileMod" type="file" name="fileMod" multiple />
            <p></p>
            <input id="check" name="checkBoxCorreggi" type="checkbox" />
            <label for="check">Correggi Checksum</label>
        </div>
    </div>
    <div class="form-group">
        <div class="col-md-10">
            <p></p>
            <input type="button" id="VerificaChecksum" value="Verifica Checksum" onclick="fileUpload()" />
            <!--value= "Verifica Checksum-->
            <p></p>
        </div>
    </div>
</form>

and a Controller like so:

public class UploadFilesController : Controller
{
    [HttpPost("UploadFiles")]
    public virtual string UploadFiles(object obj)
    {
        return "Just a test";
    }

}

What I'm trying to achieve is to passing a file from the client to the Controller, I've read a lot around but so far none has worked at all, this is my javascript code that it is supposed to call my controller:

function fileUpload() {
    var fd = new FormData();
    var xhr = new XMLHttpRequest();
    var file = document.getElementById("fileOri").files[0];
    fd.append("file", file);
    xhr.open("POST", "/Home/Dll194/UploadFiles", true);
    xhr.send()

}

But my breakpoints in VS2017 in the controller code are not being hits, am I doing something wrong? Can someone please clarify the process of sending a file to an MVC controller? I'm working with MVC and Netcore 2.1.

EDIT: By analyzing my call in Fiddler it says that the response from the call was OK (200), so I don't understand why my breakpoints on my controller are not hit. Thanks!

Tetsuya Yamamoto
  • 24,297
  • 8
  • 39
  • 61
FabioEnne
  • 732
  • 1
  • 14
  • 43
  • There is `jQuery` in your question title, but you send request with `XMLHttpRequest`. Why not `$.post()` or `$.ajax()`? – vasily.sib Mar 18 '19 at 09:09
  • @vasily.sib thanks for your response...can You provide a little example on how you would implement that? – FabioEnne Mar 18 '19 at 09:10
  • I can't see any routing, so I assume you're using the default routing. the URL in xhr.open() seems incorrect, should be /UploadFiles/UploadFiles (/Controller/Action). Also why don't you send the form via ajax? – mcb Mar 18 '19 at 09:10
  • @mcb many thanks for your reply...can you provide a little example as answer? – FabioEnne Mar 18 '19 at 09:13
  • @FabioEnne, sure. jQuery docs already have this samples for [ajax](http://api.jquery.com/jquery.ajax/) and [post](https://api.jquery.com/jquery.post/) (which is a shorthand for `ajax` actualy) – vasily.sib Mar 18 '19 at 09:27
  • well, if your controller is UploadFilesController and the Action is called UploadFiles (as in your provided example), your URL should be xhr.open("POST", "/UploadFiles/UploadFiles", true); – mcb Mar 18 '19 at 11:23

4 Answers4

1

Put the file into the request body:

var file = document.getElementById("fileOri").files[0];
var req = new XMLHttpRequest();
req.open("POST", "/Home/Dll194/UploadFiles", true);
req.setRequestHeader("File-Name", file.name);
req.setRequestHeader("File-Size", file.size);
req.send(file);

Then you can save the file in ASP.NET Core:

[HttpPost("UploadFiles")]
public virtual string UploadFiles()
{
    using (FileStream stream = new FileStream(Request.Headers["File-Name"], FileMode.Create))
    {
        await Request.Body.CopyToAsync(stream);
    }
    return "File uploaded!";
}
D.W
  • 300
  • 2
  • 13
0

Try to edit function with the following code:

xhr.send(fd)
Karol Selak
  • 4,248
  • 6
  • 35
  • 65
shinwei
  • 11
0

Take a look at this question.

In the controller:

[HttpPost("UploadFiles")]
public virtual string UploadFiles()
{
    HttpRequest request = HttpContext.Current.Request;
    var files = request.Files;
    return "Just a test";
}
ttulka
  • 10,309
  • 7
  • 41
  • 52
0

You could use ajax to pass as formdata to controller.

JS:

@section Scripts{ 
<script>
function fileUpload() {
    var input = document.getElementById("fileOri");
    var files = input.files;
    var formData = new FormData();

    for (var i = 0; i != files.length; i++) {
        formData.append("files", files[i]);
    }

    $.ajax(
        {
            url: "/Home/Upload",
            data: formData,
            processData: false,
            contentType: false,
            type: "POST",
            success: function (data) {
                alert("Files Uploaded!");
            }
        }
    );
}
</script>
}

HomeController:

[HttpPost]
public async Task<IActionResult> Upload(IList<IFormFile> files)
Ryan
  • 19,118
  • 10
  • 37
  • 53