如果您想将图像存储在服务器上,那么您的服务器应该下载文件并存储它。
下面是一个简单的示例,说明我将如何做到这一点:
const path = require('path')
const fs = require('fs')
const URL = require('url').URL
const http = require('http')
const https = require('https')
// Define a function to download images from a passed array of URL's.
const downloadImages = (arr, folderpath = '') => {
// - Create a new array of `Promise`s from the passed array, using `Array.map`
// and pass that new array to `Promise.all` so they are all waited for
// in-parallel.
// - Each `Promise` in this new array resolves when the data specified in
// the passed array `item.URL` is downloaded and saved to a file with the
// appropriate name.
return Promise.all(arr.map(item => {
// For each item in the passed array...
// Create and return a Promise which:
return new Promise((resolve, reject) => {
// Creates a `WriteStream` to a local file on path:
// '[root directory path]/[folderpath]/[item.title].[extension]'
const extension = path.extname(item.url)
const filepath = `${path.dirname(process.mainModule.filename)}${folderpath}/${item.title}${extension}`
const writeStream = fs.createWriteStream(filepath)
// Reject if there's an error acquiring or writing to the `WriteStream`.
writeStream.on('error', reject)
// - Ensure we use the appropriate http module for downloading the file.
// - If the `item.url` is HTTPS we use the `https` module, otherwise we
// use the `http` module.
const protocol = new URL(item.url).protocol
const requester = protocol === 'https:' ? https : http
// Get a stream to the data on the URL.
requester
.get(item.url, res => {
// Reject the Promise if the HTTP status code is not 200.
if (res.statusCode !== 200) {
return reject(`${item.url} failed, HTTP status: ${res.statusCode}`)
}
// Otherwise pass the stream to the `WriteStream` so it can be written
// to the local file.
res.pipe(writeStream)
// When it's done, resolve the Promise.
writeStream.on('finish', resolve)
})
.on('error', reject) // Also reject if there's a generic request error.
})
}))
}
// Test the function in an async IIFE since we are going to use await.
;(async () => {
try {
// `downloadImages` returns a Promise so we need to await it.
await downloadImages([
{
title: 'lenna-color',
url: 'https://upload.wikimedia.org/wikipedia/en/7/7d/Lenna_%28test_image%29.png'
},
{
title: 'lenna-grayscale',
url: 'https://www.ece.rice.edu/~wakin/images/lenaTest3.jpg'
}
])
console.log('done')
} catch (err) {
console.error(err)
}
})()
你关心的部分是我上面定义的downloadImages(arr, folderpath)函数。
如果要将图像保存到根目录,可以这样调用:
await downloadImages([
{
title: 'lenna-color',
url: 'https://upload.wikimedia.org/wikipedia/en/7/7d/Lenna_%28test_image%29.png'
},
{
title: 'lenna-grayscale',
url: 'https://www.ece.rice.edu/~wakin/images/lenaTest3.jpg'
}
])
或保存在根目录中名为“images”的文件夹中:
await downloadImages([
{
title: 'lenna-color',
url: 'https://upload.wikimedia.org/wikipedia/en/7/7d/Lenna_%28test_image%29.png'
},
{
title: 'lenna-grayscale',
url: 'https://www.ece.rice.edu/~wakin/images/lenaTest3.jpg'
}
], '/images')