我想直接从客户端上传图片,但我做得不好。有人能帮助我吗?
版本:
我的逻辑
客户端(反应):我正在使用react-dropzone
handleOnDrop = (files) => {
files.map(file => this.uploadImage(file))
}
uploadImage = (file) =>{
axios.get('http://localhost:3000/upload/',
{
params: {
filename: file.name
}
})
.then(res => {
const signedUrl = res.data.url;
return axios.put(signedUrl, file)
})
.then((result) => console.log(result))
.catch(e => console.log(e));
}
...
<Dropzone onDrop={this.handleOnDrop} >
服务器端(Rails)
配置
Aws.config.update({
region: 'us-east-2',
credentials: Aws::Credentials.new(ENV['AWS_ACCESS_KEY_ID'], ENV['AWS_SECRET_ACCESS_KEY']),
})
S3_BUCKET = Aws::S3::Resource.new.bucket(ENV['S3_BUCKET'])
controller
class S3Controller < ApplicationController
def upload
render json: S3_BUCKET.object("uploads/#{SecureRandom.uuid}/#{params[:filename]}").presigned_url(:get)
end
end
的routes.rb
...
get 'upload', to: 's3#upload'
...
控制器
class S3Controller < ApplicationController
def upload
render json: S3_BUCKET.object("uploads/#{SecureRandom.uuid}/#{params[:filename]}").presigned_url(:get)
end
end
错误记录
TypeError: Cannot read property 'protocol' of undefined
at isURLSameOrigin (eval at <anonymous> (webpack-bundle.self-2cf7062….js?body=1:3328), <anonymous>:57:21)
at dispatchXhrRequest (eval at <anonymous> (webpack-bundle.self-2cf7062….js?body=1:2070), <anonymous>:109:50)
at Promise (<anonymous>)
at xhrAdapter (eval at <anonymous> (webpack-bundle.self-2cf7062….js?body=1:2070), <anonymous>:12:10)
at dispatchRequest (eval at <anonymous> (webpack-bundle.self-2cf7062….js?body=1:3265), <anonymous>:52:10)
at <anonymous>