![](/img/trans.png)
[英]Error when uploading file to Google Cloud Storage in node.js
[英]How to incorporate directory names when uploading a file to google cloud storage in node.js
在我的快速服務器中,我創建了一個頁面來從本地機器上傳圖像文件。 它在我的根目錄中創建一個臨時目錄路徑,該路徑由上傳頁面中的表單數據指定。 我試圖在圖像上傳中傳遞臨時目錄名稱,但無論我做什么,它都只上傳image.jpg
而不是category/subcat/image.jpg
,沒有組織它正在上傳到的存儲桶。
表格看起來像:
<form action="/upload" method="POST">
<input type="text" name="category" autocomplete="off"/>
<input type="text" name="subcat" autocomplete="off"/>
<input type="file" id="img" name="image" accept="image/*"/>
<button type="submit">Upload</button>
</form>
使用我的代碼(使用fs
和multer
),我創建了一個如下所示的目錄路徑:
./category/subcat/image.jpg //the names are dynamically generated by the form data
這就是我希望文件添加到存儲桶時的樣子。 但是,當我上傳時,它只上傳image.jpg
而不是category/subcat/image.jpg
。
這是服務器文件中的 post 請求:
app.post("/upload", upload.single("image"), (req, res) => {
let imagePath = `${req.body.categories}/${req.body.subcat}/${req.imageName}`
async function uploadFile() {
await storage.bucket(bucketName).upload(imagePath)
}
uploadFile().catch(console.error);
res.redirect("/upload#upload");
});
知道為什么uploadFile()
沒有采用我提供的完整圖像路徑嗎? 如何修改上傳文件及其目錄的功能? 無論我添加什么到upload()
或我如何定義imagePath
它只上傳image.jpg
而不是category/subcat/img.jpg
。
如果要指定上傳文件的目標路徑,則需要將第二個參數傳遞給upload() ,這是一個UploadOptions對象。 您可以看到它有一個名為destination
的屬性:
保存文件的地方。 如果給定一個字符串,文件將使用該字符串作為文件名上傳到存儲桶。 當給定一個 File 對象時,您的本地文件將被上傳到 File 對象的存儲桶並在 File 對象的名稱下。 最后,當省略此參數時,文件將使用本地文件的名稱上傳到您的存儲桶。
由於您沒有提供目的地,因此將您提供的文件的基本名稱作為默認值。 你應該簡單地提供你想要的路徑名:
storage.bucket(bucketName).upload(imagePath, { destination: "path/you/choose.jpg" })
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.