我正在嘗試從 url 地址下載影像并將其保存在我的服務器中。例如,我使用影像的 URL 發出 POST 請求。我下載影像并將其保存在我的服務器中。當我需要弄清楚影像的擴展時,問題就來了。現在它只適用于 jpg 檔案,但它也適用于 png 檔案。如何在保存檔案之前找出檔案的擴展名?
一種方法是從 url 本身獲取擴展名,但并非所有 url 都有擴展名,例如:https : //media.istockphoto.com/photos/winter-in-the-sequoias-picture-id1292624259
這是我現在制作的代碼。它有效,但我怎么說,它是靜態的,僅適用于 jpg:
var config = {
responseType: 'stream'
};
async function getImage(url) {
let time = Math.floor(Date.now() / 1000)
let resp = await axios.get(url, config)
resp.data.pipe(fs.createWriteStream(time '.jpg')) // here I need to get the image extension isntead of static '.jpg'
}
uj5u.com熱心網友回復:
您可以為此使用回應標頭。該Content-Type的標題應該告訴你的檔案的型別和內容處置,你可以得到擴展的檔案名。
在您的代碼中,您可以像這樣訪問這些標頭
resp.headers['content-type'];
resp.headers['content-disposition'];
uj5u.com熱心網友回復:
我建議使用諸如mime 之類的模塊從內容型別中獲取擴展名。
完整示例:
const axios = require('axios');
const fs = require('fs');
const mime = require('mime');
var config = {
responseType: 'stream'
};
async function getImage(url) {
let time = Math.floor(Date.now() / 1000)
let resp = await axios.get(url, config)
const contentLength = resp.headers['content-length'];
const contentType = resp.headers['content-type'];
const extension = mime.extension(contentType);
console.log(`Content type: ${contentType}`);
console.log(`Extension: ${extension}`);
const fileName = time "." extension;
console.log(`Writing ${contentLength} bytes to file ${fileName}`);
resp.data.pipe(fs.createWriteStream(fileName));
}
const url = 'https://media.istockphoto.com/photos/winter-in-the-sequoias-picture-id1292624259';
getImage(url)
這將給出類似于以下內容的輸出:
內容型別:影像/jpeg 擴展名:jpeg 將 544353 位元組寫入檔案 1638867349.jpeg
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/376466.html
標籤:javascript 节点.js 图片 公理
下一篇:如何在c#中裁剪帶有多邊形的影像
