<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<style>
body {
font-family: "Arial",sans-serif;
}
.dropzone {
width: 300px;
height: 300px;
border: 2px dashed #ccc;
color: #ccc;
line-height: 300px;
text-align: center;
}
.dropzone.dragover {
border-color: #000;
color: #000;
}
</style>
</head>
<body>
<div id="uploads"></div>
<div class="dropzone" id="dropzone">Drop files here to append file</div>
<ul id="files-to-upload"></ul>
<input type="text" name="tags" id="tags" value="blue,whatever" />
<input type="text" name="name" id="name" value="name" />
<button onclick="onUpload()">upload</button>
<script>
var dropzone = document.getElementById('dropzone'),
filesToUpload = document.getElementById('files-to-upload'),
fileArr = [];
var appendFiles = function (files) {
console.log(files);
for (var i = 0; i < files.length; i++) {
filesToUpload.insertAdjacentHTML('beforeend', '<li>' + files[i].name + '</li>');
fileArr.push(files[i]);
}
};
var onUpload = function () {
var xhr = new XMLHttpRequest(), formData = new FormData();
for (var i = 0; i < fileArr.length; i++) {
formData.append('files', fileArr[i]);
}
// append metadata
formData.append('tags', document.getElementById('tags').value);
formData.append('name', document.getElementById('name').value);
console.log(formData);
//
xhr.onload = function () { // success
var data = this.responseText;
while (filesToUpload.firstChild) { // faster than "filesToUpload.innerHTML = '';"
filesToUpload.removeChild(filesToUpload.firstChild);
}
fileArr = []; // empty file list
console.log(data);
};
xhr.open('post', '/Home/Upload');
xhr.send(formData);
}
dropzone.ondrop = function (e) {
e.preventDefault(); // 避免瀏覽器開啟圖片
this.className = 'dropzone';
appendFiles(e.dataTransfer.files);
};
dropzone.ondragover = function () {
this.className = 'dropzone dragover';
return false;
};
dropzone.ondragleave = function () {
this.className = 'dropzone';
return false;
};
</script>
</body>
</html>
=========================
後端 ASP.NET Core
[HttpPost]
public async Task<IActionResult> Upload(ICollection<IFormFile> files, string tags, string name)
{
foreach (var file in files)
{
if (file.Length > 0)
{
using (var fileStream = new FileStream(Path.Combine("wwwroot/images", file.FileName), FileMode.Create))
{
await file.CopyToAsync(fileStream);
}
}
}
return Content("A12345678");
}