I have this html form which I want to post data and files to C# Web Api. Here is my front-end code
document.getElementById("form1").addEventListener("submit", function (e) {
e.preventDefault();
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]);
}
var tags = $('#tags').val();
formData.append("tags", tags);
$.ajax(
{
url: "https://localhost:44371/api/file/upload",
processData: false,
contentType: false,
type: "POST",
data: formData,
dataType: 'json',
success: function () {
alert("Files Uploaded!");
}
}
);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="form1">
<div class="form-group">
<div class="buttons">
<div class="upload-button">
<input id="files" name="files" type="file" size="1" />
</div>
</div>
</div>
<div class="form-group">
<label for="tags">Tags:</label>
<input type="text" class="form-control" id="tags">
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary" id="btnSave">Upload and Save</button>
</div>
</form>
And here is my back-end Web Api C# code:
[HttpPost]
[Route("upload")]
public async Task<ActionResult<FileDocument>> PostFileDocument(List<IFormFile> files, string tags)
{
return Ok("test");
}
I can reach this method and I can see files has data. But tags is showing null. But I have appended tags at formData.append("tags", tags);. I googled and some said put [FromBody] List<IFormFile> files which I have tried but when I did, it became null.