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!

6
  • There is jQuery in your question title, but you send request with XMLHttpRequest. Why not $.post() or $.ajax()? Commented Mar 18, 2019 at 9:09
  • @vasily.sib thanks for your response...can You provide a little example on how you would implement that? Commented Mar 18, 2019 at 9: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? Commented Mar 18, 2019 at 9:10
  • @mcb many thanks for your reply...can you provide a little example as answer? Commented Mar 18, 2019 at 9:13
  • @FabioEnne, sure. jQuery docs already have this samples for ajax and post (which is a shorthand for ajax actualy) Commented Mar 18, 2019 at 9:27

4 Answers 4

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!";
}
Sign up to request clarification or add additional context in comments.

Comments

0

Try to edit function with the following code:

xhr.send(fd)

2 Comments

this should be a comment, not an answer
@bradbury9 new users need 50 reputation to add a comment, but you are right - answers shouldn't say "Try".
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";
}

Comments

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)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.