The backend configuration

Upload file must be a POST request, here we use KOA to implement a simple POST request, and let the front end of the formData data sent and do some simple processing;

const Koa = require('koa');
const Router = require('koa-router');
const koaBody = require('koa-body');

let app = new Koa();
let router = new Router();  app.use(koaBody({  multipart: true // Allow clients to upload files }));  router.post('/upload'.async (ctx, next) => {  // The files uploaded by the client will be stored in this object ctx.request.files  // Read this file and save it to the upload folder  let data = fs.readFileSync(ctx.request.files.image.path);  fs.writeFileSync(path.join(__dirname, 'upload', ctx.request.files.image.name), data);  ctx.body = { status: 1 }; });  app.use(router.routes()); app.listen(3000); Copy the code

The front-end realizes single file upload

The front end uses a FormData object and an XMLHttpRequest object to implement file uploads

Here we do not consider the style first, just simple implementation of the function

<input type="file" />
<button>Click on the upload</button>
Copy the code
document.querySelector('button').onclick = function () {
  // It gets a files array object because it's a single file upload and it takes the first one
  let file = document.querySelector('input').files[0];
  let xhr = new XMLHttpRequest();
  xhr.open('post'.'/upload'.true);
 xhr.onload = function () {  let res = JSON.parse(xhr.responseText);  console.log(res);  }   let form = new FormData();  form.append('image', file); // Corresponding key value  xhr.send(form); } Copy the code

At this point, the file has been uploaded and saved by the server; We can add some extensions, such as a progress bar and upload speed.

Single file upload speed and progress bar

HTML optimization part: here the progress bar, we will be based on html5 native progress tag to achieve;

<input type="file" />
<progress value="0" max="100"></progress>
<span class="percent">0%</span>
<span class="speed">0 b/s</span>
<button>Click on the upload</button>
Copy the code

Js bedding; If we want to know the upload progress and the current download speed, we must do the following things;

  • Monitor the status of uploaded files

Xhr. upload has hooks for file upload. We can use these hook functions to monitor the progress bar

https://developer.mozilla.org/zh-CN/docs/Web/API/XMLHttpRequest/upload


  • Gets the size of the file total
  • Gets the size of the current download

Can get to the total through the event hooks and the size of https://developer.mozilla.org/zh-CN/docs/Web/API/XMLHttpRequestEventTarget/onprogress

let startTime;
let startSize;
document.querySelector('button').onclick = function () {
  // It gets a files array object because it's a single file upload and it takes the first one
  let file = document.querySelector('input').files[0];
 let xhr = new XMLHttpRequest();  xhr.open('post'.'/upload'.true);  xhr.onload = function () {  let res = JSON.parse(xhr.responseText);  console.log(res);  }   let form = new FormData();  form.append('image', file); // Corresponding key value   xhr.upload.onloadstart = function () {  // Start uploading hooks  startTime = new Date().getTime();  startSize = 0;  }  xhr.upload.onprogress = function (event) {  // Hook is being uploaded and will be called many times  // Amount of data transferred/Total amount of data * 100  let percent = (event.loaded / event.total * 100).toFixed(0);  document.querySelector('progress').value = percent;  document.querySelector('.percent').innerHTML = percent + The '%';   let currentTime = new Date().getTime();  let dtime = (currentTime - startTime) / 1000; // Time difference s  startTime = new Date().getTime(); // Get the time again after the calculation is complete   let dsize = event.loaded - startSize; // size difference b  startSize = event.loaded; // Retrieve the strip after the calculation is complete   let speed = dsize / dtime; / / speed  let unit = 'b/s'; / / unit  // Base calculation  if (speed / 1024 > 1) {  speed = speed / 1024;  unit = 'kb/s';  }  if (speed / 1024 > 1) {  speed = speed / 1024;  unit = 'mb/s';  }   document.querySelector('.speed').innerHTML = speed.toFixed(2) + unit;  }  // Reset the progress bar after uploading  xhr.onload = function () {  document.querySelector('progress').value = 0;  document.querySelector('.percent').innerHTML = 0 + The '%';  document.querySelector('.speed').innerHTML = '0b/s';  }  xhr.send(form); } Copy the code

Axios Single file upload with progress bar

Progress is monitored in AXIos via the onUploadProgress hook

axios.post('/upload', form, {
  onUploadProgress: event= > {
    let complete = (event.loaded / event.total * 100 | 0)
    document.querySelector('progress').value = complete;
    document.querySelector('.percent').innerHTML = complete + The '%';
 if (complete >= 100) {  document.querySelector('progress').value = '0';  document.querySelector('.percent').innerHTML = 0 + The '%';  }  }, }).then(res= > {  console.log(res) }); Copy the code

Results show

This article is formatted using MDNICE