React Native上传至AWS S3前重命名拍摄图片的方法
Hey there! Great job getting the basic S3 upload working—let's tweak your code to rename those images exactly how you want before sending them up.
The Key Idea
When you create the file object after taking a photo, instead of using the auto-generated response.fileName, you'll construct your own custom name using the device ID, geolocation context, and a unique timestamp. AWS S3 uses the name field from your file object as the filename in the bucket, so that's where we'll make our change.
Step-by-Step Changes
- Store Device ID in State Early
First, let's grab the device ID and save it to state so it's ready when you take a photo. Update yourcomponentDidMountmethod:
componentDidMount() { // Existing geolocation logic navigator.geolocation.getCurrentPosition( (position) => { this.setState({ latitude: position.coords.latitude, longitude: position.coords.longitude, error: null, }); }, (error) => this.setState({ error: error.message }), { enableHighAccuracy: true, timeout: 20000 }, ); // Add this line to get and save the device ID const deviceId = DeviceInfo.getUniqueID(); this.setState({ deviceId }); }
- Modify
takePicto Rename the Image
This is where we'll build your custom filename. We'll use the device ID, a timestamp for uniqueness, and preserve the original file extension (or force PNG if you prefer):
takePic(){ ImagePicker.launchCamera({},(response)=>{ console.log(response); // Extract original file extension (fallback to PNG if none found) const fileExtension = response.fileName?.split('.').pop() || 'png'; // Generate a unique timestamp (you could use server time instead if needed) const timestamp = new Date().getTime(); // Build your custom filename matching your example format const customFileName = `${this.state.deviceId}_geolocation_${timestamp}.${fileExtension}`; const file ={ uri : response.uri, name : customFileName, // Use our new custom name here! method: 'POST', path : response.path, type : response.type, notification: { enabled: true } } console.log('File prepared for upload:', file); // Update state correctly (avoid direct array pushes to state!) this.setState(prevState => ({ saveImages: [...prevState.saveImages, file] })); }) }
Optional: Force All Images to PNG Format
If you want every uploaded image to be a PNG regardless of the original format, adjust the code like this:
const customFileName = `${this.state.deviceId}_geolocation_${timestamp}.png`; const file ={ // ...other fields type : 'image/png', // Update MIME type to match PNG format }
Why This Works
- The
nameproperty in thefileobject dictates what the file will be called in your S3 bucket. By replacing the auto-generated name with your custom string, S3 will store the file exactly as you want it. - We're using
setStatewith the previous state to update thesaveImagesarray—this is the proper React way to modify state arrays, ensuring components re-render when changes happen (directpushto state doesn't trigger updates).
Final Note
Your existing _upload method doesn't need any changes—it will automatically use the renamed files from your saveImages state array.
内容的提问来源于stack exchange,提问作者Vidya

