LoginSignup
0
1

More than 3 years have passed since last update.

WEBアプリケーションに画像をアップロードする機能を実装する方法

Last updated at Posted at 2021-04-13

WEBアプリケーションに画像をアップロードする機能を実装する方法

Javaを利用して作成したWEBアプリケーションに画像投稿機能を実装する際の手順について記載します

イメージとしては下記の図のようなイメージになります。
Something went wrong

画像のアップロードにはHTMLのformタグとinputタグを利用します

フロントエンド
<form method="post" >
  <input type="file" name="uploadImage" />
  <input type="submit" value="送信" />
</form>

Something went wrong

バックエンド側では、Fileクラスを利用して受け取ります

バックエンド
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // Fileクラスのインスタンス化(保存するディレクトリの指定)
    File uploadDir = new File("/Users/test/Documents/app/WebContent/images");
    // リクエストパラメーターから画像の取得
    Part fPart = request.getPart("uploadImage");
    // 画像の名前を決める
    String fName = "testphoto";
    // 保存処理の呼び出し
    save(fPart, new File(uploadDir, fName));

//保存処理
public void save(Part in, File out) throws IOException {
    BufferedInputStream br = new BufferedInputStream(in.getInputStream());
    try (BufferedOutputStream bw = new BufferedOutputStream(new FileOutputStream(out))) {
        int len = 0;
        byte[] buff = new byte[1024];
        while ((len = br.read(buff)) != -1) {
            bw.write(buff, 0, len);
        }
    }
}

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1