Skip to content

Instantly share code, notes, and snippets.

@damienpontifex
Last active August 24, 2017 03:25
Show Gist options
  • Save damienpontifex/6d8cf0399b28a631c879f75483dd1bb1 to your computer and use it in GitHub Desktop.
Save damienpontifex/6d8cf0399b28a631c879f75483dd1bb1 to your computer and use it in GitHub Desktop.
Drag and drop upload of files to ASP.NET API endpoint. Streams file vs using a FormData instance
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace server.Controllers
{
[Route("api/[controller]")]
public class FilesController : ControllerBase
{
[HttpPost("{filename}")]
public async Task<IActionResult> Post(string filename)
{
var filepath = System.IO.Path.Combine(System.IO.Directory.GetCurrentDirectory(), filename);
using (var file = new FileStream(filename, FileMode.Create))
{
await Request.Body.CopyToAsync(file);
return Ok();
}
}
}
}
<!DOCTYPE html>
<html>
<head>
<style>
/* https://www.youtube.com/watch?v=299RZ0d1LQY */
html {
/* Background for overscroll - should match nav color */
background: red;
}
body {
min-height: 100vh;
position: relative;
margin: 0;
background-color: cadetblue;
box-sizing: border-box;
}
.dragging {
border: 2px solid red;
}
main {
padding: 1em;
}
</style>
</head>
<body>
<main>
<h4>Uploaded Files</h4>
<ul id="fileList">
</ul>
</main>
<script>
(function () {
var uploadedFileList = document.getElementById('fileList');
// https://www.youtube.com/watch?v=y1BsexcSW8o
document.addEventListener('dragenter', function (event) {
event.preventDefault();
if (event.dataTransfer.types.indexOf('Files') !== -1) {
// Feedback for file dragging
document.body.classList.add('dragging');
}
});
['dragleave', 'drop'].forEach(function (eventName) {
document.addEventListener(eventName, function () {
document.body.classList.remove('dragging');
});
});
document.addEventListener('dragover', function (event) {
event.preventDefault();
});
function appendFileToList(file) {
var listItem = document.createElement('li');
listItem.innerHTML = file.name;
listItem.setAttribute('name', file.name);
uploadedFileList.appendChild(listItem);
return listItem;
}
function uploadFile(file) {
var listItem = appendFileToList(file);
var xhr = new XMLHttpRequest();
xhr.upload.onprogress = function (e) {
if (e.lengthComputable) {
var percentage = Math.round((e.loaded * 100.0) / e.total);
console.log(percentage, '% uploaded');
listItem.innerHTML = file.name + ': ' + percentage + '% uploaded';
}
};
xhr.upload.onload = function (e) {
console.log('onload');
};
xhr.open('POST', 'http://localhost:5000/api/Files/' + file.name);
if (file.type) {
xhr.overrideMimeType(file.type);
}
xhr.send(file);
}
document.addEventListener('drop', function (event) {
event.preventDefault();
var droppedFiles = event.dataTransfer.files;
for (var idx = 0; idx < droppedFiles.length; idx++) {
uploadFile(droppedFiles[idx]);
}
});
})();
</script>
</body>
</html>
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
namespace server
{
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddCors();
services.AddMvc();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseCors(builder =>
{
builder.AllowAnyOrigin()
.AllowAnyHeader()
.AllowAnyMethod();
});
app.UseMvc();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment