简体   繁体   中英

Send post data with file upload AJAX

I am currently sending a file via AJAX like this:

var fd = new FormData();

    //do stuff to that adds files

    var xhr = new XMLHttpRequest();
    xhr.open('POST', '/Upload/' + ID);
    xhr.send(fd);

And using the file in my contoller like:

HttpPostedFileBase file = Request.Files[i];

This all works fine but I want to send more information. How can I post more variables along with the file?

use variable name in xhr.send() . Like xhr.send(var1=fd&var2=anotherdata) . Then at your server side create two POST data handlers, namely var1 & var2 . One will hold fd and other will hold extra data.

var fd = new FormData();

    //do stuff to that adds files
    fd.append("Variable1", "data");
    var xhr = new XMLHttpRequest();
    xhr.open('POST', '/Upload/' + ID);
    xhr.send(fd);

This worked best for me.

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