2016-03-08 118 views
0

我想上傳圖片到Amazon S3,如果可能的話可以在任何一個提供如何上傳到Amazon S3鏈接/文檔,任何幫助非常感謝上傳圖片到Amazon S3的反應母語

+0

向下突破您的問題分成更小的部件和工作每一個出來。 1)反應本地網絡。 2)在反應本地網絡框架中上傳文件。 3)亞馬遜S3 API。另外,我不確定這個問題對於SO是有益的。 – Poutrathor

+0

你能分享你最終使用的解決方案嗎? – Marklar

回答

2

S3選項:

// this.state.s3options in YourComponent 
{ 
    "url": "https://yourapp.s3.eu-central-1.amazonaws.com", 
    "fields": { 
    "key": "cache/22d65141b48c5c44eaf93a0f6b0abc30.jpeg", 
    "policy": "eyJleHBpcm...1VDE0Mzc1OVoifV19", 
    "x-amz-credential": "AK...25/eu-central-1/s3/aws4_request", 
    "x-amz-algorithm": "AWS4-HMAC-SHA256", 
    "x-amz-date": "20161125T143759Z", 
    "x-amz-signature": "87863c360...b9b304bfe650" 
    } 
} 

組件:

class YourComponent extends Component { 
    // ... 

    // fileSource looks like: {uri: "content://media/external/images/media/13", isStatic: true} 
    async uploadFileToS3(fileSource) { 
    try { 
     var formData = new FormData(); 
     // Prepare the formData by the S3 options 
     Object.keys(this.state.s3options.fields).forEach((key) => { 
     formData.append(key, this.state.s3options.fields[key]); 
     }); 
     formData.append('file', { 
     uri: fileSource.uri, 
     type: 'image/jpeg', 
     }); 
     formData.append('Content-Type', 'image/jpeg') 

     var request = new XMLHttpRequest(); 
     request.onload = function(e) { 
     if (e.target.status === 204) { 
      // Result in e.target.responseHeaders.Location 
      this.setState({avatarSourceRemote: {uri: e.target.responseHeaders.Location}}) 
     } 
     }.bind(this) 
     request.open('POST', this.state.s3options.url, true); 
     request.setRequestHeader('Content-type', 'multipart/form-data'); 
     request.send(formData); 
    } catch(error) { 
     console.error(error); 
    } 
    } 

    // Example display the uploaded image 
    render() { 
    if (this.state.avatarSourceRemote) { 
     return (
     <Image source={this.state.avatarSourceRemote} style={{width: 100, height: 100}} /> 
    ); 
    } else { 
     return (
     <Text>No Image</Text> 
    ); 
    } 
    } 
}