Send the picture to the background, don’t know how to get the content of the picture.

  node.js, question

The traditional way to send pictures to the background is to send them directly using a form with input of type file. Now I want to use an input to realize ajax sending. I don’t know what post used to be and how to get this content.

  1. For asynchronous upload, if you still want to upload files directly, you can use HTML5FormDataFor details, please refer to this blog. …

  2. I also have another way to upload pictures asynchronously. First, convert the picture into base64 string, and then submit base64 string to the server. After the server receives it, it can convert base64 string into picture content with specific API. The following are specific implementation methods:

var getObjectURL = function(file) {
 var url = null;
 if (window.createObjectURL !  == undefined) { // basic
 url = window.createObjectURL(file);
 } else if (window.URL !  == undefined) { // mozilla(firefox)
 url = window.URL.createObjectURL(file);
 } else if (window.webkitURL !  == undefined) { // webkit or chrome
 url = window.webkitURL.createObjectURL(file);
 return url;

getObjectURLThe method is used to convert the picture file object in the incoming input into a temporary url, which is the same domain.

var converImgTobase64 = function(url, callback, outputFormat) {
 var canvas = document.createElement('CANVAS'),
 ctx = canvas.getContext('2d'),
 img = new Image;
 img.crossOrigin = 'Anonymous';
 img.onload = function(){
 canvas.height = img.height;
 canvas.width = img.width;
 var dataURL = canvas.toDataURL(outputFormat || 'image/png');, dataURL);
 canvas = null;
 img.src = url;

converImgTobase64The method is to pass in the url obtained above and convert it into base64 string through canvasAPI. Note that this url must be the same domain and cannot cross domains, sogetObjectURLThis method is very necessary.


var input = $("input[type=file]")[0],
 src = getObjectURL(input.files[0]);
 converImgTobase64(src, function(base64Str) {
 //Handling base64Str-related callback, ajax requests can be sent directly here.

The code of this part of components is in one of my util libraries. please refer to it and put forward rectification opinions ~ ~ ~ …