What is the process for updating AWS s3 object metadata while uploading an image through a PUT request to a signed URL?

Is there a way to include the uploaded file name in AWS S3 with a random or unique identifier within a NextJS application?

I am able to set metadata from the backend, but I want to know how to update it during the PUT request when the image is being uploaded to the signed URL. Can this be achieved?

To clarify: I want to modify metadata while making a PUT request to the signed URL. Currently, I have set it to "none" on the backend to prevent forbidden errors (which appears as metadata in S3). Is it possible to change this metadata during the PUT request, or should I consider another approach? Thank you!

// Backend code for obtaining signed URL

async function handler(req, res) {
  if (req.method === 'GET') {
    const key = `content/${uuidv4()}.jpeg`;

    s3.getSignedUrl(
      'putObject',
      {
        Bucket: 'assets',
        ContentType: 'image/jpeg',
        Key: key,
        Expires: 5 * 60, 
        Metadata: {
          'file-name': "none",
        }
      },
      (err, url) => res.send({ key, url }) 
    );
  }
// Frontend code 

const [file, setFile] = useState(null);

const onFileUpload = async (e) => {
    e.preventDefault();

    const uploadConfig = await fetch('/api/upload');
    const uploadURL = await uploadConfig.json();

    await fetch(uploadURL.url, {
      body: file,
      method: 'PUT',
      headers: {
        'Content-Type': file.type,
        'x-amz-meta-file-name': 'updated test name',
      },
    });
  };

Answer №1

When dealing with presigned URLs, it's important to note that once created, all properties are fixed and cannot be changed during the file uploading process. The bucket, key, metadata, and other parameters of put_object are predetermined when generating a presigned URL, as well as for generate_presigned_post.

This approach makes sense, as it allows the back-end to grant permissions accordingly and simplifies implementation, considering the various client methods with different parameters that presigned URLs support.

If you do need to modify these properties dynamically, one workaround is to generate URLs on-demand. By first creating a presigned URL based on client-selected criteria, you can then proceed with the upload process. However, this method requires two separate round-trips - one to your server for URL generation and another to S3 for actual uploading.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Encountered a problem while attempting to start the npm http-server

My project is built on node.js and Angular 2, initially served using lite-server. Now, I need to serve server-side files, so I am switching to http-server. Previously, I used the command "start": "tsc && concurrently \"tsc -w\" \"lite-server ...

I'm facing difficulty transferring information to another component

I'm currently using Next.js with TypeScript and Material UI. I have created a component called MyOrders and I am trying to pass data from MyOrders to MyOrderItem. However, I am encountering an issue where I am unable to pass the data to MyOrderItem. ...

Setting a fresh keybinding in Atom on macOS

Recently, I decided to switch over to using Atom on my Macbook and I wanted to set up a keybinding where alt-up arrow would act as page up and alt-down arrow for page down. Despite my efforts, I have not been successful in getting this to work. I'm p ...

Issue TS8011 in Angular 6 is related to the restriction on using type arguments only in files with the .ts extension

I have a project in Angular 6 where I need to integrate a JS library. This library is confidential, so I can't disclose its details. The problem I'm facing is that the TypeScript compiler seems to misinterpret characters like <<24>>, ...

Locate within an array of mongoose subdocuments to extract an array of documents that share common fields

Here are my database schemas along with the associated queries: (list's id and a question topic). The questionSchema is nested within the listSchema. const questionSchema = new mongoose.Schema({ topic: { type : String , unique : false , required : ...

What is the best way to iterate through an array in Vue using only half the number of iterations as the total number of items?

My data is stored in an array: [ { type: select, options: [foo, bar], label: foo, required: true }, { type: text, options: [], label: bar, required: false }, { type: checkbox, options: [], lab ...

How can I resolve the error when Model.findOne() does not support a callback anymore?

I am facing an issue with this code as it is returning the error "Model.findOne() no longer accepts a callback". I need to resolve this issue without downgrading my mongoose version. `router.post('/login', async(req, res) => { const email = r ...

Executing mathematical operations with floating point numbers using JavaScript in Python

I’m creating a Python program that interacts with a web application that I didn’t develop. There is some data that needs to be represented in my program which isn’t directly sent to the client by the server, but is instead calculated separately on bo ...

Lens Flare Troubles in Three JS

I'm having trouble implementing the LensFlare Effect from the three js docs in react three fiber. I've tried using the code provided but it's not working for me. Here's what I have: import { extend, useLoader } from "@react-three/f ...

Discord.js unable to locate a non-existent folder

I am currently developing a Discord Bot using Discord.js, and I have a feature that sends a random image from a pre-defined set. Here's the code snippet: client.on('message', msg => { if (msg.content === 'I Hate It'){ ...

Executing an asynchronous function in React within the same file

Having trouble calling the removeCouponCode method from the same file, as the execution claims it's not defined. I'm unsure of what might be missing here. Any suggestions? Below is the file I am working on and attempting to modify. Not entirely c ...

Is it possible to retrieve the value of a session attribute set by a servlet in an HTML page using JavaScript?

As a beginner in programming, I am facing an issue with transferring data from a servlet to an HTML page. My servlet forwards to the HTML page using redirect, but I need to access the attribute "poNumber" in my session attributes and display its value on t ...

React components exhibiting duplicate file upload behavior

Introducing my new creation, the ImageSelector, a versatile image upload tool designed for a custom CMS. This component allows users to select a header image and multiple images for a gallery effortlessly. https://i.sstatic.net/YMN1U.png Incorporating th ...

strange issue: functional code snippet does not seem to be working on the HTML page

Strange occurrence. I am facing an issue where my code at http://jsfiddle.net/48Hpa/19/ does not seem to be working properly when I transfer it to HTML at http://jsbin.com/AYEQEJE/1/edit. I have thoroughly checked everything including the DOM readiness, b ...

Integrating Typeform into a React application with a custom button component

I'm facing a challenge with integrating a Typeform contact form into my Gatsby React website. Most of the examples I've come across demonstrate using a basic html button, which doesn't align with the overall theme of my website. Below is the ...

Issue: $injector:unpr Unrecognized Provider: itemslistProvider <-

I've spent several days debugging the code, but I can't seem to find a solution. I've gone through the AngularJS documentation and numerous Stack Overflow questions related to the error, yet I'm still unable to identify what's caus ...

How can I modify this section of the code in Google Script to retrieve all columns?

My question is, how can I modify this code to fetch all columns from the array instead of just [0,1,2,3] Here is the line of code in question: const new_table = [0,1,2,3].map(x => make_row_from_col(this_table, x)).join('\n'); Using obje ...

Tips for rendering only certain sections of a partial view?

Currently, I am in the process of developing a web application that utilizes jquery 1.9.1 and jquery mobile 1.3.2 within Visual Studio (MVC4 template). Throughout the application, there are numerous pages with a side panel feature. While the side panel con ...

Switch up and Combine Functions Producing the Initial Array

I recently encountered an issue with reversing and joining an array in JavaScript. I had an array named arr with values [a, a, b, c, d]. My intention was to reverse the array and then join it together to create a string. Here is the code snippet I used: a ...

Encountering a Netlify build issue while trying to import web3 in a NextJS project - 'Encountered an error: Unable to resolve 'electron' in...'

Currently, I am working on a web page that utilizes web3 for interacting with Ethereum smart contracts. During the Netlify build process, I encountered errors whenever I tried to import web3 into the page: 9:54:39 PM: ModuleNotFoundError: Module not found: ...