简体   繁体   中英

Post more than one parameter for file upload to the web api

I have this html form which let user upload a file and also another extra input type for extra info about this upload.

<form method="post" enctype="multipart/form-data">
       <input id="files" name="files" type="file" size="1" />           
       <input type="text" id="tags">           
       <button type="submit" id="btnSave" onchange="uploadFiles();">Upload and Save</button>        
</form>

and this is my javascript

function uploadFiles() {
    var input = document.getElementById('files');
    var files = input.files;
    var formData = new FormData();

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

    $.ajax(
        {
            url: "https://localhost:xxx/api/file/upload",
            data: formData,
            processData: false,
            contentType: false,
            type: "POST",
            success: function () {
                alert("Files Uploaded!");

            }
        }
    );
}

My question is how do I add others parameters (ie tags here) to post to web api and at the same time upload the file? Post the request at complex type? Any example for complex type which include file upload?

You just can append new properties there. formdata append will help you to add string and file

formData.append("tags",document.getelementbyid('tags').value);

this is some source to read about FormData https://developer.mozilla.org/en-US/docs/Web/API/FormData

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