Implementation of JavaScript downloading linked images and uploading them

Implementation of JavaScript downloading linked images and uploading them

Since we are going to upload pictures, the first thing we need to do is to determine whether it is a downloadable picture resource. Sometimes we can use regular expressions, but it is difficult to determine whether it is downloadable. It is also difficult to determine whether there is a suffix after the picture link. Some pictures do not have a suffix, but if this restriction is lifted, it is easier to be attacked. So here we use Image as a judgment method. If the picture is loaded successfully, it means that it is indeed a picture and can be downloaded.

// Check if the link points to an image 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("Sorry, this link cannot retrieve the image");
 });

After making the judgment, we need to download the image. Here we use XMLHttpRequest to request the download, and the downloaded image will be a Blob object.

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

// Make an XMLHttpRequest request to the image in the image link and return a 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();
 });
}

// Convert the Blob object to a File object const blobToFile = (blob: Blob, fileName: string) => {
 return new window.File([blob], fileName, { type: blob.type });
};

// how to use it
// Returns a File object that can be used for upload operations getImageBlob(src).then(async (res: any) => {
 const srcSplit = src.split("/");
 const filename = srcSplit[srcSplit.length - 1];
 return blobToFile(res, filename);
});

The following is a small demonstration of uploading OSS. Since OSS involves a lot of private information, it is recommended that you use the interface to obtain information such as accessKeyId and accessKeySecret, or even use temporary keys.

import OSS from "ali-oss";

const ERROR_TIP = "Upload failed!";

/**
 * Example of uploading a file to OSS* The relevant accessKeyId, bucket and other parameters need to be filled in according to your OSS library* It is recommended to make the two sensitive information [accessKeyId, accessKeySecret] into an interface to obtain or encrypt*/
export const uploadToOSS = async (
 fileName: string,
 file: File,
 accessKeyId: string,
 accessKeySecret: string,
 ...props
) => {
 let client = new OSS({
  endpoint, // The OSS project address bucket you applied for, // 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 convert the Blob format file into FormData format and use XMLHttpRequest or Ajax to upload the picture.

// Convert the Blob object to a 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 backend project, I used Express as a static image library. The following is my node code for uploading images. It is worth noting that after using formidable parsing, the jpg file will have a long random name directly in your preset photo directory. In fact, I also used a shorter name for renaming here. You can choose the renaming strategy according to your needs.

const express = require("express");
const listenNumber = 5000;
const app = express();
const bodyParser = require("body-parser");
const http = require("http"); //Create a server 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 picture 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"; //Set the edit form.keepExtensions = true; //Retain the 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: "" });
   }
  });
 });
});

This is the end of this article about the implementation of JavaScript downloading link images and uploading them. For more related JavaScript downloading link images and uploading content, please search 123WORDPRESS.COM’s previous articles or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Jsp page to achieve file upload and download class code
  • JSP program example to implement file upload and download
  • jsp file upload and download example code
  • The json data returned by the uploaded file will be prompted to download the problem solution
  • WeChat java implements js-sdk picture upload and download complete process
  • Native js implements example methods such as file upload, download, and packaging

<<:  Complete steps to configure a static IP address for a Linux virtual machine

>>:  Example of using MySQL to count the number of different values ​​in a column

Recommend

WeChat applet implements simple calculator function

This article shares the specific code for the WeC...

MySQL Best Practices: Basic Types of Partition Tables

Overview of MySQL Partitioned Tables As MySQL bec...

ElementUI implements the el-form form reset function button

Table of contents Business scenario: Effect demon...

What hidden attributes in the form can be submitted with the form

The form elements with visibility=hidden and displ...

jQuery achieves full screen scrolling effect

This article example shares the specific code of ...

How to implement vue page jump

1. this.$router.push() 1. Vue <template> &l...

Shorten the page rendering time to make the page run faster

How to shorten the page rendering time on the bro...

How to adapt CSS to iPhone full screen

1. Media query method /*iPhone X adaptation*/ @me...

Writing and understanding of arrow functions and this in JS

Table of contents Preface 1. How to write functio...

react-beautiful-dnd implements component drag and drop function

Table of contents 1. Installation 2.APi 3. react-...

Methods for optimizing Oracle database with large memory pages in Linux

Preface PC Server has developed to this day and h...

How to click on the a tag to pop up the input file upload dialog box

html Copy code The code is as follows: <SPAN cl...

Apache Calcite code for dialect conversion

definition Calcite can unify Sql by parsing Sql i...

Detailed explanation of custom swiper component in JavaScript

Table of contents Effect display Component Settin...