终于解决了问题!我希望这个答案可以帮助其他尝试解决此问题的人,因为没有足够的资源。令我惊讶的是,我发现其他人也想这样做。我对Carrierwave初始化文件的原始更改似乎已死胡同。
最终的结果是在控制器中创建了上传的图像对象,然后将其注入到参数中。
对于此特定示例,我们将获取一个base64文件(我假设您具有,因为JSON不支持嵌入文件),并将其另存为系统中的临时文件,然后创建该UploadedFile对象,最后将其重新注入到参数。
我的json / params看起来像什么:
picture {:user_id => "1", :folder_id => 1, etc., :picture_path {:file => "base64 awesomeness", :original_filename => "my file name", :filename => "my file name"}}
这是我的控制器现在的样子:
40 # POST /pictures41 # POST /pictures.json42 def create43 44 #check if file is within picture_path45 if params[:picture][:picture_path]["file"]46picture_path_params = params[:picture][:picture_path]47#create a new tempfile named fileupload48tempfile = Tempfile.new("fileupload")49tempfile.binmode50#get the file and depre it with base64 then write it to the tempfile51tempfile.write(base64.depre64(picture_path_params["file"]))52 53#create a new uploaded file54uploaded_file = ActionDispatch::Http::UploadedFile.new(:tempfile => tempfile, :filename => picture_path_params["filename"], :original_filename => picture_path_params["original_filename"]) 55 56#replace picture_path with the new uploaded file57params[:picture][:picture_path] = uploaded_file58 59 end60 61 @picture = Picture.new(params[:picture])62 63 respond_to do |format|64 if @picture.save65 format.html { redirect_to @picture, notice: 'Picture was successfully created.' }66 format.json { render json: @picture, status: :created, location: @picture }67 else68 format.html { render action: "new" }69 format.json { render json: @picture.errors, status: :unprocessable_entity }70 end71 end72 end
此时,剩下要做的唯一一件事就是删除临时文件,我相信可以用
tempfile.delete
希望这对您的问题有所帮助!昨天我整天都在寻找解决方案,而我所看到的一切都是死胡同。但是,这适用于我的测试用例。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)