既然要進行圖片上傳,那么第一時間當然是判斷是否為可下載的圖片資源,有的時候可以使用正則表達式,但是很難判斷是否可下載,當判斷圖片鏈接后是否有后綴的時候也比較苦惱,有的圖片是沒有后綴的,可是如果放開這個限制又比較容易被攻擊,所以這里我們使用 Image 作為判斷手法,若成功加載圖片,那么說明確實為圖片且可下載。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
|
// 判斷鏈接是否指向圖片且可下載 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( "很抱歉, 該鏈接無法獲取圖片" ); }); |
判斷好后,我們需要對這個圖片進行下載,這里我們使用 XMLHttpRequest 進行請求下載,下載后會是一個 Blob 對象。
Blob 本身可以轉化成 FormData 對象或者是 File 對象,我們可以根據自己項目的具體情況去選擇上傳策略,如果想傳到 OSS 上,可以選擇轉化為 File 對象,若是傳輸到自己的服務器上,可以使用 Ajax,并轉 Blob 為 FormData 進行上傳。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
|
// 將圖片鏈接中的圖片進行 XMLHttpRequest 請求,返回Blob對象 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(); }); } // 將Blob對象轉為File對象 const blobToFile = (blob: Blob, fileName: string) => { return new window.File([blob], fileName, { type: blob.type }); }; // how to use it // 返回一個File對象,可使用該 File 對象進行上傳操作 getImageBlob(src).then(async (res: any) => { const srcSplit = src.split( "/" ); const filename = srcSplit[srcSplit.length - 1]; return blobToFile(res, filename); }); |
接下來是一個上傳OSS的小演示,由于 OSS 涉及的隱私信息較多,所以建議大家把accessKeyId、accessKeySecret等信息用接口去獲取,甚至使用臨時的鑰匙等。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
|
import OSS from "ali-oss" ; const ERROR_TIP = "上傳失敗!" ; /** * File上傳OSS的示例 * 相關accessKeyId、bucket等參數需要根據你的OSS庫進行填寫 * 建議將【accessKeyId,accessKeySecret】這兩個敏感信息做成接口獲取或者加密 */ export const uploadToOSS = async ( fileName: string, file: File, accessKeyId: string, accessKeySecret: string, ...props ) => { let client = new OSS({ endpoint, // 你申請好的oss項目地址 bucket, // OSS 對象載體 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); }; |
當然如果想上傳圖片到你自己的服務器,可以選擇將 Blob 格式的文件轉為 FormData 格式,使用 XMLHttpRequest 或者 Ajax 進行圖片的上傳
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
|
// 將Blob對象轉為FormData對象 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); }, }); }; |
在之前我的后端項目中,使用了 Express 作為靜態圖片庫,以下是我的 node 上傳圖片代碼。值得注意的是,使用 formidable 解析后,jpg 文件會直接在你的預設照片目錄有一個很長的隨機名稱,這邊其實我也是使用了較短的名稱進行重命名,大家可以根據自己的需要選擇重命名策略。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
|
const express = require( "express" ); const listenNumber = 5000; const app = express(); const bodyParser = require( "body-parser" ); const http = require( "http" ); //創建服務器的 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()); //數據JSON類型 // 上傳圖片 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; //設置上傳文件的緩存目錄 form.encoding = "utf-8" ; //設置編輯 form.keepExtensions = true ; //保留后綴 form.maxFieldsSize = 2 * 1024 * 1024; //文件大小 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: "" }); } }); }); }); |
到此這篇關于JavaScript 下載鏈接圖片后上傳的實現的文章就介紹到這了,更多相關JavaScript 下載鏈接圖片后上傳內容請搜索服務器之家以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持服務器之家!
原文鏈接:https://juejin.cn/post/6936459869432053791