Implementation of uploading link pictures after downloading JavaScript

  • 2021-11-01 02:02:03
  • OfStack

Since you want to upload pictures, Then, of course, the first time is to judge whether it is a downloadable picture resource. Sometimes you can use regular expressions, However, it is difficult to judge whether it can be downloaded. It is also distressing to judge whether there is a suffix after the picture is linked. Some pictures have no suffix, but if this restriction is released, it is easier to be attacked. Therefore, we use Image as a judgment technique here. If the picture is successfully loaded, it means that it is indeed a picture and can be downloaded.


//  Determine whether the link points to the picture and can be downloaded 
export const checkImgExists = (imgurl: string) => {
 return new Promise(function (resolve, reject) {
  var ImgObj = new Image();
  ImgObj.src = imgurl;
  ImgObj.onload = function (res) {
   resolve(res);
  };
  ImgObj.onerror = function (err) {
   reject(err);
  };
 });
};

// how to use it
checkImgExists(imgLink)
 .then(() => {
  // do something with imgLink
  console.log(imgLink);
 })
 .catch((err) => {
  // some log or alarm
  console.log(err);
  console.log(" I'm sorry ,  This link cannot get pictures ");
 });

After judging, we need to download this picture. Here we use XMLHttpRequest to request download, and after downloading, it will be an Blob object.

Blob itself can be converted into FormData object or File object. We can choose upload strategy according to the specific situation of our project. If we want to transmit it to OSS, we can choose to convert it to File object. If it is transmitted to our own server, we can use Ajax and transfer Blob to FormData for uploading.


//  The picture in the picture link is carried out  XMLHttpRequest  Request, return Blob Object 
function getImageBlob(url: string) {
 return new Promise(function (resolve, reject) {
  var xhr = new XMLHttpRequest();
  xhr.open("get", url, true);
  xhr.responseType = "blob";
  xhr.onload = function () {
   if (this.status == 200) {
    resolve(this.response);
   }
  };
  xhr.onerror = reject;
  xhr.send();
 });
}

//  Will Blob Object conversion File Object 
const blobToFile = (blob: Blob, fileName: string) => {
 return new window.File([blob], fileName, { type: blob.type });
};

// how to use it
//  Return 1 A File Object, you can use the  File  Object for upload operation 
getImageBlob(src).then(async (res: any) => {
 const srcSplit = src.split("/");
 const filename = srcSplit[srcSplit.length - 1];
 return blobToFile(res, filename);
});

Next is a small demonstration of uploading OSS. Because OSS involves more private information, it is recommended that you use interfaces to obtain accessKeyId, accessKeySecret and other information, and even use temporary keys.


import OSS from "ali-oss";

const ERROR_TIP = " Upload failed! ";

/**
 * File Upload OSS Example of 
 *  Correlation accessKeyId , bucket Equal parameters need to be based on your OSS Fill in the library 
 *  It is suggested that " accessKeyId , accessKeySecret "These two sensitive information are made into interfaces to obtain or encrypt 
 */
export const uploadToOSS = async (
 fileName: string,
 file: File,
 accessKeyId: string,
 accessKeySecret: string,
 ...props
) => {
 let client = new OSS({
  endpoint, //  You apply well oss Project address 
  bucket, // OSS  Object carrier 
  accessKeyId, // your accessKeyId with OSS
  accessKeySecret, // your accessKeySecret with OSS
  internal: true,
  ...props,
 });
 const putResult = await client.put(fileName, file, {
  timeout: 60 * 1000 * 2,
 });
 if (putResult.res.status === 200) {
  return { url: putResult.url, fileName };
 }
 throw new Error(ERROR_TIP);
};

Of course, if you want to upload pictures to your own server, you can choose to change files in Blob format to FormData format, and use XMLHttpRequest or Ajax to upload pictures


//  Will Blob Object conversion FormData Object 
const blobToFormData = (blob: Blob, fileName: string) => {
 const formdata = new FormData();
 formdata.append("file", blob, fileName);
 return formdata;
};

// XMLHttpRequest
const uploadFile = (formData: FormData) => {
 const url = "your_interface";
 let xhr = new XMLHttpRequest();
 xhr.onload = function () {
  console.log("ok");
  console.log(JSON.parse(xhr.responseText));
 };
 xhr.onerror = function () {
  console.log("fail");
 };
 xhr.open("post", url, true);
 xhr.send(formData);
};

// Ajax
const uploadFile2 = (formData: FormData) => {
 const url = "your_interface";
 $.ajax({
  url,
  type: "POST",
  data: formData,
  async: false,
  cache: false,
  contentType: false,
  processData: false,
  success: function (returndata) {
   console.log(returndata);
  },
  error: function (returndata) {
   console.log(returndata);
  },
 });
};

In my previous back-end project, I used Express as a static picture library. Here is my node upload picture code. It is worth noting that after using formidable parsing, jpg file will have a long random name directly in your default photo directory. In fact, I also used a shorter name to rename here, so you can choose the renaming strategy according to your own needs.


const express = require("express");
const listenNumber = 5000;
const app = express();
const bodyParser = require("body-parser");
const http = require("http"); // To create the server's 
const formidable = require("formidable");
const path = require("path");
const fs = require("fs");
app.use(express.static("../../upload"));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json()); // Data JSON Type 

//  Upload pictures 
app.post("/upLoadArticlePicture", (req, res, next) => {
 let defaultPath = "../../upload/";
 let uploadDir = path.join(__dirname, defaultPath);
 let form = new formidable.IncomingForm();
 let getRandomID = () =>
  Number(Math.random().toString().substr(4, 10) + Date.now()).toString(36);
 form.uploadDir = uploadDir; // Set the cache directory for uploaded files 
 form.encoding = "utf-8"; // Setting Edit 
 form.keepExtensions = true; // Retain suffix 
 form.maxFieldsSize = 2 * 1024 * 1024; // File size 
 form.parse(req, function (err, fields, files) {
  if (err) {
   res.locals.error = err;
   res.render("index", { title: TITLE });
   return;
  }
  let filePath = files.file["path"];
  let backName = filePath.split(".")[1];
  let oldPath = filePath.split("\\")[filePath.split("\\").length - 1];
  let newPath = `${getRandomID()}.${backName}`;
  fs.rename(defaultPath + oldPath, defaultPath + newPath, (err) => {
   if (!err) {
    newPath = `http://localhost:${listenNumber}/${newPath}`;
    res.json({ flag: true, path: newPath });
   } else {
    res.json({ flag: false, path: "" });
   }
  });
 });
});

Related articles: