我添加了将Base64图像与Carrierwave结合使用的解决方案,以尝试从Java类上传图像。现在这是我的FileUploader类的样子-
我认为问题出在哪里:
# encoding: utf-8
class FileUploader < CarrierWave::Uploader::Base
# Include RMagick or MiniMagick support:
include CarrierWave::RMagick
# include CarrierWave::MiniMagick
# Choose what kind of storage to use for this uploader:
storage :file
# storage :fog
#START FROM BASE64 POST LINKED ABOVE
class FilelessIO < StringIO
attr_accessor :original_filename
attr_accessor :content_type
end
before :cache, :convert_base64
def convert_base64(file)
if file.respond_to?(:original_filename) &&
file.original_filename.match(/^base64:/)
fname = file.original_filename.gsub(/^base64:/, '')
ctype = file.content_type
decoded = Base64.decode64(file.read)
file.file.tempfile.close!
decoded = FilelessIO.new(decoded)
decoded.original_filename = fname
decoded.content_type = ctype
file.__send__ :file=, decoded
end
file
end
#END FROM POST LINKED ABOVE
# Override the directory where uploaded files will be stored.
# This is a sensible default for uploaders that are meant to be mounted:
def store_dir
"uploads/#{model.class.to_s.underscore}/#{model.user_id}"
end
# Provide a default URL as a default if there hasn't been a file uploaded:
# def default_url
# "/images/fallback/" + [version_name, "default.png"].compact.join('_')
# end
# Process files as they are uploaded:
# process :scale => [200, 300]
#
# def scale(width, height)
# # do something
# end
# Create different versions of your uploaded files:
version :thumb do
process :resize_to_fit => [200, 300]
end
version :web do
process :resize_to_fit => [1000, 1000]
end
# Add a white list of extensions which are allowed to be uploaded.
# For images you might use something like this:
def extension_white_list
%w(jpg jpeg gif png)
end
# Override the filename of the uploaded files:
# Avoid using model.id or version_name here, see uploader/store.rb for details.
def filename
if original_filename
Time.new.to_i.to_s+"_"+original_filename
end
end
end
图片型号:
class Picture < ActiveRecord::Base
belongs_to :user
belongs_to :folders
attr_accessible :user_id, :picture_name, :picture_description,
:folder_id, :picture_path, :file_save
mount_uploader :picture_path, FileUploader
before_save :update_pictures_attributes
def update_pictures_attributes
self.file_size = picture_path.file.size
end
end
现在,当进行Post调用时,保存在数据库中的文件路径为nil,但其他所有内容均已保存。这是java / android类:
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.client.*;
import org.apache.http.client.entity.*;
import org.apache.http.client.methods.*;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.*;
import org.apache.http.message.*;
import org.apache.commons.io.FileUtils;
import org.json.*;
import android.util.Base64;
import android.util.Log;
public class Uploader {
private String url;
private String fileName;
public Uploader(String url, String fileName){
this.url = url;
this.fileName = fileName;
}
public Boolean upload() throws JSONException, ClientProtocolException, IOException {
Boolean success = true;
JSONObject jsonObject = constructPictureJson();
DefaultHttpClient httpClient = new DefaultHttpClient();
ResponseHandler <String> responseHandler = new BasicResponseHandler();
HttpPost postMethod = new HttpPost(url);
postMethod.setEntity(new StringEntity(jsonObject.toString()));
postMethod.setHeader("Accept", "application/json");
postMethod.setHeader("Content-type", "application/json");
postMethod.setHeader("Data-type", "json");
try{
httpClient.execute(postMethod, responseHandler);
} catch (org.apache.http.client.HttpResponseException error){
Log.d("Uploader Class Error", "Error code: "+error.getStatusCode());
Log.d("Uploader Class Error", "Error message: "+error.getMessage());
success = false;
}
//Log.d("server resposne", response);
return success;
}
public JSONObject constructPictureJson() throws JSONException, IOException{
String userId = "1";
String folderId = "1";
String[] file = fileName.split("/");
JSONObject pictureData = new JSONObject();
pictureData.put("user_id", userId);
pictureData.put("folder_id", folderId);
pictureData.put("picture_name", "picture name");
pictureData.put("picture_description", "1");
pictureData.put("content_type", "jpg");
pictureData.put("original_filename", "base64:"+file[file.length-1]);
pictureData.put("filename", file[file.length-1]);
pictureData.put("picture_path", encodePicture(fileName));
return pictureData;
}
public String encodePicture(String fileName) throws IOException{
File picture = new File(fileName);
return Base64.encodeToString(FileUtils.readFileToByteArray(picture), Base64.DEFAULT);
}
}
有人有什么想法吗?我整天都被困住了。我想是因为我对Ruby不太了解,所以我要么(1)伪造了请求;要么
或(2)我用Carrierwave错误地实现了base64映像。
终于解决了问题!我希望这个答案可以帮助其他尝试解决此问题的人,因为没有足够的资源。令我惊讶的是,我发现其他人也想这样做。我对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 /pictures
41 # POST /pictures.json
42 def create
43
44 #check if file is within picture_path
45 if params[:picture][:picture_path]["file"]
46 picture_path_params = params[:picture][:picture_path]
47 #create a new tempfile named fileupload
48 tempfile = Tempfile.new("fileupload")
49 tempfile.binmode
50 #get the file and decode it with base64 then write it to the tempfile
51 tempfile.write(Base64.decode64(picture_path_params["file"]))
52
53 #create a new uploaded file
54 uploaded_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 file
57 params[:picture][:picture_path] = uploaded_file
58
59 end
60
61 @picture = Picture.new(params[:picture])
62
63 respond_to do |format|
64 if @picture.save
65 format.html { redirect_to @picture, notice: 'Picture was successfully created.' }
66 format.json { render json: @picture, status: :created, location: @picture }
67 else
68 format.html { render action: "new" }
69 format.json { render json: @picture.errors, status: :unprocessable_entity }
70 end
71 end
72 end
此时,剩下要做的唯一一件事就是删除临时文件,我相信可以用 tempfile.delete
希望这对您的问题有所帮助!昨天我整天都在寻找解决方案,而我所看到的一切都是死胡同。但是,这适用于我的测试用例。
问题内容: 我一直在寻找这个东西,对我没有任何帮助。 我正在尝试将图像从android应用上传到java servlet并将其保存在服务器中。我发现的每个解决方案都不适合我。 我的代码当前正在执行的操作:android应用程序正在将图像发送到servlet,当我尝试保存该图像时,该文件已创建,但它是空的:( 谢谢你的帮助! 我在android客户端中的代码(i_file是设备上的文件位置): 我在
问题内容: 我正在尝试从Android设备将文件上传到php服务器。有相同问题的话题,但他使用的是不同的方法。我的Android辅助代码运行正常,并且未显示任何错误消息,但服务器未收到任何文件。这是我的示例代码,我在网上找到了。 和我的PHP服务器端代码如下 Apache正在运行。当我运行服务器时,出现此错误消息。上传文件时出错,请重试!我已经在eclipse中检查了日志数据,我认为是套接字问题,
日安!我正在尝试搜索一个从Android上传一个图像文件到一个在线MySQL数据库的基本教程,但是我找不到任何。 我现在正在做一个activity,可以把用户的个人资料图片从Android上传到在线服务器上。 我需要的是像显示一个按钮,当它被点击时,用户可以从文件中选择一个图像。有人能指导我做这件事吗?提前道谢!
正如上面的问题所描述的,我正在尝试将一个文件从okhttp3上传到服务器。 我总是收到‘你没有选择一个文件上传’在我的方法从codeIgniter部分。 这是我的代码 Android: 服务器代码: 我做错了什么?谢谢!
问题内容: 昨天我做了一个深夜的编码会议,并创建了一个小的node.js / JS(实际上是CoffeeScript,但是CoffeeScript只是JavaScript,所以可以说是JS)应用程序。 目标是什么: 客户端(通过socket.io)将canvas datauri(png)发送到服务器 服务器将图像上传到亚马逊s3 步骤1完成。 服务器现在有一个字符串 我的问题是: 将数据“流” /
问题内容: 我是具有网络服务的android新手 我试图将arraylist从android传递到webservice php服务器 这是我的bean代码: 这是我在异步任务上的doInBackround: 这是storeHistoryList方法: 我想将列表传递给Web服务 list是一个arraylist ExpressionBean 我用gson将bean转换为json 但是当我执行时,日