React Dropzone组件:如何动态修改postUrl?
First, let's break down your issues and fix them step by step:
1. Fix the Immediate TypeError
The Uncaught TypeError: Cannot read property 'url' of undefined error comes from your initial this.dropzone value — you set it to the string 'null' instead of the actual null value. When the config() function runs on component initialization, this.dropzone is still that string, so trying to access this.dropzone.options.url fails (strings don't have an options property).
2. Fix Dynamic Per-File Upload URLs
Your core goal is to use a unique presigned URL for each file, but trying to update the global postUrl via this.dropzone.options.url won't work — the postUrl in the component config is a static initialization value. Instead, you need to override the upload URL per individual file right before it starts processing, which Dropzone.js (the underlying library) supports directly.
Here's the revised, working code:
class Uploader extends React.Component { constructor(props) { super(props); // Fix: Initialize dropzone as null (not a string) this.dropzone = null; } config = () => ({ iconFiletypes: ['.jpg', '.png', '.gif'], showFiletypeIcon: true, // Use a placeholder URL — we'll override per file later postUrl: 'placeholder-url' }); eventHandlers = () => ({ // Keep this to reference the dropzone instance if needed elsewhere init: dz => this.dropzone = dz, }); djsConfig = (requestID = this.props.requestId) => ({ addRemoveLinks: false, acceptedFiles: "image/jpeg,image/png,image/gif", autoProcessQueue: true, init: function () { this.on("processing", async (file) => { // Fetch the unique presigned URL for this specific file const presigned_url = await uploadUrl(file, requestID, () => {}); // Critical: Override the URL for THIS FILE only // Dropzone.js lets you set file.upload.url directly to target individual uploads file.upload.url = presigned_url; // Optional: Add custom headers if your presigned URL requires them // file.upload.headers = { 'X-Amz-Content-Sha256': 'UNSIGNED-PAYLOAD' }; }); } }); render() { // Don't forget to render the DropzoneComponent with your configs return ( <DropzoneComponent config={this.config()} eventHandlers={this.eventHandlers()} djsConfig={this.djsConfig()} /> ); } }
Key Changes Explained:
- Corrected Dropzone Initialization: Swapped
'null'fornullto avoid trying to access properties on a string. - Placeholder PostUrl: The
postUrlinconfig()is just a placeholder since we'll override each file's URL individually. - Per-File URL Override: Setting
file.upload.urldirectly ensures each file uses its own unique presigned URL, instead of modifying a global setting that would affect all files.
This approach works because Dropzone.js processes each file independently, and updating file.upload.url right before processing tells the library to use that specific URL for only that file's upload.
内容的提问来源于stack exchange,提问作者peebee

