画像ファイルのアップロード方法
ImagePickerプラグインで画像を選択した後、選択した画像をアップロードする場合には、FileTransferプラグインを利用します。
ImagePickerプラグインを利用した画像の選択方法についてはこちらを参照。
なお、サーバ側の画像データ受け取りにはRubyのSinatraを使用しています。
目次
- FileTransferプラグインのインストール・設定
- サンプル
- サーバ側に送られてきた画像の保存
FileTransferプラグインのインストール・設定
サンプル
選択した画像ファイル1件を送信する場合のサンプルコードです。
var params = {};
params.uid = 1;
var options = new FileUploadOptions();
options.fileKey = "file";
options.fileName = $scope.imageUrl.substr($scope.imageUrl.lastIndexOf('/') + 1);
options.mimeType = "text/plain";
options.params = params;
var ft = new FileTransfer();
ft.upload(
$scope.imageUrl,
encodeURI("http://localhost/save_image/")), // サーバ側のURL
function (r) {
console.log(r);
var res = JSON.parse(r.response); // r.responseにはサーバからの戻り値が格納されている
if(res.success) {
// 成功
alert("画像の登録に成功しました。");
} else {
// 失敗
alert(res.error_message);
}
},
function (error) {
// エラー
console.log(error);
},
options);
13行目のURLにはサーバ側のURLを設定してください。
サーバ側に送られてきた画像の保存
サーバ側にはRubyのSinatraを利用しています。
以下のコードは、クライアントから送られてきた画像ファイルを、サーバ側の特定のディレクトリにファイルとして保存しているサンプルコードです。
# 画像の登録
post '/save_image/' do
res = {}
begin
# 画像の保存
if params[:file]
file_name = params[:file][:filename]
file_temp = params[:file][:tempfile]
#file_type = params[:file][:type]
file_ext = File.extname(file_name)
# 拡張子のチェック
extensions = [".jpeg", ".jpg", ".png"]
if !extensions.include?(file_ext)
raise "image extension not allowed, please choose a jpeg or png."
end
# ファイルサイズのチェック
if file_temp.size > 1048576
raise "File size over."
end
# ファイルの保存(ファイル名は「ユーザーID_年月日_時分秒_ミリ秒」)
file_path = "var/www/example/images/" + params[:uid] + "_" + Time.now.strftime("%Y%m%d_%H%M%S_%L") + file_ext
File.open(file_path, 'wb') do |f|
f.write file_temp.read
end
else
# ファイルが送られてきていない
raise "Image not found."
end
res["success"] = true
rescue => ex
res["success"] = false
res["error_message"] = ex.message
ensure
end
content_type :json, :charset => 'utf-8'
res.to_json(:root => false)
end
拡張子やファイルサイズのチェックは必要であれば行ってください。