2016-03-08 92 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> 
    ); 
    } 
    } 
}