简体   繁体   中英

How to incorporate directory names when uploading a file to google cloud storage in node.js

In my express server I have created a page to upload image files from a local machine. It creates a temporary directory path in my root directory that is specified by the form data from the upload page. I am trying to pass in the temporary directory names in the image upload, but no matter what I do it only uploads image.jpg instead of category/subcat/image.jpg , giving no organization to the bucket it is being uploaded to.

The form looks like:

  <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>

With my code (using fs and multer ) I create a directory path that looks like:

./category/subcat/image.jpg    //the names are dynamically generated by the form data

This is what I want the file to look like when it is added to the bucket. However, when I upload, it is only uploading image.jpg and not category/subcat/image.jpg .
Here is the post request in the server file:

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");
});

Any idea why the uploadFile() is not taking the full image path I am providing? How can I amend the function to upload a file with it's directories? No matter what I add to upload() or how I define imagePath it only uploads image.jpg instead of category/subcat/img.jpg .

If you want to specify the destination path of the uploaded file, you will need to pass a second argument toupload() , which is a UploadOptions object. You can see that it has a property called destination :

The place to save your file. If given a string, the file will be uploaded to the bucket using the string as a filename. When given a File object, your local file will be uploaded to the File object's bucket and under the File object's name. Lastly, when this argument is omitted, the file is uploaded to your bucket using the name of the local file.

Since you are not providing a destination, it's taking the basename of the file you provided as the default. You should simply provide the path name you want:

storage.bucket(bucketName).upload(imagePath, { destination: "path/you/choose.jpg" })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM