Recently encountered such a requirement (as shown in the title), a brief note
Now to introduce in detail how to implement a requirement, the front-end to upload an image, the backend access to a folder, and stored in front can via http://127.0.0.1:3000/images/1632830606327.jpg (example) to get to the backend that picture
The specific effects are as follows:
We use native JS + native Node to achieve this requirement
The front end
Let’s start with a simple demo of uploading pictures
< input type = "file" id = "ABC" accept = "image/jpeg image/JPG, image/PNG" > < button onclick = "submited ()" > upload < / button > < br / > < img SRC ="" Alt ="" id="showImg" width="350"Copy the code
We won’t have to explain too much about this step, but we’ll go straight to the next step. After that, you can expect to get the uploaded image information. In this case, we use the FileReader FileReader to read the file and convert it to base64 format.
let file = document.getElementById('abc').files[0];
let showImg = document.getElementById('showImg')
let reader = new FileReader();
if (file) {
reader.readAsDataURL(file);
reader.onload = function () {
console.log(reader.result); //返回的是转成base64格式后的图片
}
}
Copy the code
After processing the basic data, it’s time to initiate the interface request
Function submited() {let file = document.getelementById (' ABC ').files[0]; let showImg = document.getElementById('showImg') let reader = new FileReader(); if (file) { reader.readAsDataURL(file); reader.onload = function () { // console.log(reader.result); Let baseImg = reader.result.replace(/^data:image\/ w+; base64,/,""); Let XHR = new XMLHttpRequest(); / / native js initiate interface request XHR. Open (' post ', 'http://127.0.0.1:3000/showImg'); Xhr.send (baseImg); Xhr.onreadystatechange = function () {// Register the event if (xhr.readyState == 4&&xhr.status == 200) {// showimg.src = xhr.responseText; // Assign the processed URL to the SRC of the img tag on the page display}}}}}Copy the code
That’s pretty much the end of the front end, but to recap what the front end does: grab locally uploaded images via FileReader, convert them to Base64 format using the readAsDataURL (BLOB) method, and finally make interface requests using native JS
The back-end
Let’s deal with some logic on the back end: Start a 3000 port service through HTTP, then use Buffer (about Buffer) to parse and process the image information sent from the front end, and then use fs module contained in Node to parse and download the data processed by Buffer (a returned Buffer instance).
Start a service for port 3000
let http = require('http'); let server = http.createServer((req, res) => { }); Server.listen (3000, () => {console.log(' service started '); })Copy the code
Then the createServer does the following logical operations. The front-end and back-end start different ports, resulting in cross-domain
Res. writeHead(200, {' content-type ': 'text/plain',// set the request header Type to "access-Control-allow-origin ": "*"//* means that all fields are allowed to request.Copy the code
The front-end makes a request to the /showImg interface, and we make a POST request
if (req.url == '/showImg' && req.method == 'POST') { let data = ''; Req. on('data', cur => {data += cur; / / post request, data will be segmented transmission}) the req. On (' end '() = > {/ / / / data after receiving call setPic (data, res); This is the data parsing operation later})}Copy the code
The file format of the backend is as follows
We converted the data that was sent to us and downloaded it into images
function setPic(data,res) { const path_1 = './images/' + Date.now() + '.jpg'; // Rename picture with timestamp const picture = path_1.replace(/\./, 'http://127.0.0.1:3000'); // This is the information returned to the front-end const dataBuffer = buffer. from(data, 'base64'); Fs.writefile (path_1, dataBuffer, function (err) {if (err) {res.end(err)}}); res.end(picture); }Copy the code
Some basic logic is almost done, front-end upload image, back-end fetch rename and download. And then there’s oursKey stepsThis is what I do. When I recognize an interface request, I call this function to match the URL, and continue if the URL contains the file name to store the image
Server on (' request '(the req, res) = > {the if (the req. Url. Match (/ \ / images /)) {/ / equivalent images file exposed the fs. ReadFile ('.' + req.url,(err,data)=>{ if(err){ console.log(err); }else{ res.end(data); }})}})Copy the code
So far have been finished all logic, can now be accessed through http://127.0.0.1:3000/images/ picture name to images
Write in the back
This is for native Nodes, but for Express and KOA it’s much easier to set up a static file manager
express
const path = require('path') const express = require('express'); app.use('/images',express.static(path.join(__dirname, 'images')));; // App.listen (3000,() => {console.log(' service started '); })Copy the code
koa
Install the plugin via NPM I koa-static or YARN Add koa-static
Const Koa = require(' Koa ') const app = new Koa() app.use(require(' Koa -static')(__dirname + '/images'))// Manage static filesCopy the code
It seems to me that all three are the same, all by exposing static folders for access.