我可以通过postman
成功地将图像上传到Amazon s3存储桶。我正在使用active storage
概念。当我使用react扩展前端时,如何存储图像以反应状态,并将其发送到params到rails后端。
答案 0 :(得分:1)
我使用一个名为react-dropzone的软件包来删除状态文件存储中的一些繁琐部分,以及将图像从React上传到API。
这是您想要做的一个非常概念示例:
import React, { Component } from "react";
import PropTypes from "prop-types";
import Dropzone from "react-dropzone";
export default class UploadImage extends Component {
state = {
files: []
};
onDrop = (files) => {
// Get existing files from state
// (or just the empty array if there are no files in state)
var currentFiles = this.state.files;
// Push file(s) from function parameters to `currentFiles` array
const [newFiles] = files;
currentFiles.push(newFiles);
// Assign files dropped into component into state
this.setState({
files: currentFiles
});
// Attempt to upload the files.
// If you want to upload after a button click, move the code
// below to its own function and have it run after button click.
if (files.length) {
let formPayLoad = new FormData();
// I'm using "avatar" here for the attribute name of the model that
// will store the image. Change the first parameter of the 'append' function
// below to be the name of the attribute name that fits your Rails model.
formPayLoad.append("avatar", files[files.length - 1]);
// Pass the data to your own defined upload function
// that makes the call to your API. Make sure you put the
// formPayLoad in the body of the request.
this.props.upload(formPayLoad);
}
}
render() {
return (
<div className="upload-image-component">
<Dropzone
onDrop={this.onDrop}
multiple={true}
>
<p>Text that says to upload file.</p>
</Dropzone>
</div>
);
}
}
然后让您的Rails控制器接受我们在上面的'onDrop'的'append'函数中定义的属性。在我的示例中,我使用的是“头像”。另一个非常概念性的示例:
class UserController < ApiController
# your actions
private
def user_params
params.permit(
# all your other params
:avatar
)
end
end