Last active
April 1, 2017 10:29
-
-
Save fumiya-kume/1f64f0011009c1478c127ef316aeb636 to your computer and use it in GitHub Desktop.
Android-Java で画像ファイルを Azure Blob Storageへアップロードする ref: http://qiita.com/fumiya-kume/items/8c7969a7a5a2f081a022
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// import は省略 | |
public class MainActivity extends AppCompatActivity { | |
public Button Button; | |
@Override | |
protected void onCreate(Bundle savedInstanceState) { | |
super.onCreate(savedInstanceState); | |
setContentView(R.layout.activity_main); | |
Button = (Button) findViewById(R.id.button); | |
Button2.setOnClickListener(new View.OnClickListener() { | |
@Override | |
public void onClick(View v) { | |
// UIスレッドでネットワークを使った重い処理を実行させるとつらみが発生するため、別スレッドで実行 | |
AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>() { | |
@Override | |
protected Void doInBackground(Void... params) { | |
// Azure Blob Storage と接続するための文字列、チョー重要。 Root アカウントのパスワードぐらい重要です。 | |
String storageConnectionString = "Connection String"; | |
// DCIM へのパスを取得 | |
File dir = new File(Environment.getExternalStorageDirectory() + "/" + Environment.DIRECTORY_DCIM); | |
// DCIM 上の画像ファイルへのパスを設定 | |
File file = new File(dir.getAbsolutePath() + "/image.jpeg"); | |
// 正しい画像へのパスが取れているか確認のためにログ出力 | |
Log.d("画像を表示させるやつ", file.getPath()); | |
try { | |
// Azure Storage Account との接続を開始 | |
CloudStorageAccount storageAccount = CloudStorageAccount.parse(storageConnectionString); | |
// Azure Storage Account の Blob との接続するためのクライアントを取得 | |
CloudBlobClient blobClient = storageAccount.createCloudBlobClient(); | |
// Blob のコンテナーを取得している、コンテナーの指定は文字列で行う | |
CloudBlobContainer container = blobClient.getContainerReference("mspjp"); | |
// getBlockBlobReference の引数で渡している文字列が、 Blob 内に保存されるファイル名になる。 | |
// すでに同じ名前のファイルが存在するときは、上書きされる | |
CloudBlockBlob blob = container.getBlockBlobReference("myimage.jpg"); | |
// ファイルが存在しなかったら 関数を終了させる | |
if (!file.exists()) return null; | |
// Azure Blob Storage へアップロード | |
blob.upload(new java.io.FileInputStream(file), filelength()); | |
} catch (Exception e) { | |
// エラーが起きたら解析用にスタックトレースを吐かせる | |
e.printStackTrace(); | |
} | |
return null; | |
} | |
}; | |
try { | |
// 別スレッドで実行させる | |
task.execute(); | |
} catch (Exception e) { | |
Handler handler = new Handler(); | |
handler.post(new Runnable() { | |
// エラーが発生したらトーストでエラーメッセージを表示させたいが、 | |
// UI スレッドでなければ、トーストを表示させれないため、 UI スレッドで実行している | |
@Override | |
public void run() { | |
Toast.makeText(MainActivity.this, "Faild: Upload blob storage", Toast.LENGTH_LONG).show(); | |
} | |
}); | |
} | |
} | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment