[英]Upload file to rails 6 api backend from react-native using axios
我想使用 axios 將帶有數據的圖像上傳到我的 rails 6 api。 我嘗試使用 formdata,但出現ActiveSupport::MessageVerifier::InvalidSignature
錯誤。 這是我的代碼:
uploadToServer= () => {
const file =this.state.photo
let formdata = new FormData()
formdata.append('name', this.state.name)
formdata.append('photo', file)
axios.post(
'api',
formdata,
{
headers: {
'Content-type' : 'multipart/form-data',
'Authorization':'xx'
}
}
).then(resp => console.log(resp)).catch(error => console.error(error));
}
這是我收到的錯誤:
Completed 500 Internal Server Error in 171ms (ActiveRecord: 46.0ms | Allocations: 32866)
ActiveSupport::MessageVerifier::InvalidSignature (ActiveSupport::MessageVerifier::InvalidSignature):
很感謝任何形式的幫助。 提前致謝
我在 reactjs 中遇到了同樣的問題。 我認為你的照片文件應該是一個“ blob ”文件。 我是這樣解決的
import Resizer from 'react-image-file-resizer';
imageInputHandler = (event) =>{
var fileInput = false
if(event.target.files[0]) {
fileInput = true
}
if(fileInput) {
Resizer.imageFileResizer(
event.target.files[0],
800,
800,
'JPEG',
100,
0,
uri => {
console.log("ok....resized")
this.setState({
file: uri
})
},
'blob',
200,
200,
);
}
}
然后像這樣使用fetch()
將參數發送到 Rails API
const formData = new FormData();
formData.append('text', self.state.text);
formData.append('user_id', self.props.user_id);
formData.append('image', self.state.image);
fetch('http://localhost:3000/posts/create', {
method: 'POST',
body: formData
})
但是當然不在同一個事件處理程序中,因為狀態還沒有更新,而且它起作用了。 出於某種原因,我既不能使用 axios 也無法做到。
並且不要忘記允許 Rails 控制器中的參數
def create
@post=Post.create(post_params)
image_url=rails_blob_path(@post.image , only_path: true) if @post.image.attached?
render json: {text: @post.text, image: image_url, user_id: @post.user_id, id:@post.id }
end
private
def post_params
params.permit( :text, :user_id, :image )
end
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.