JavaのWebアプリケーション開発フレームワークによる、Webサイト開発の顛末記です。

EclipseのMavenを使った、Spring-MVC、Thymeleaf、MyBatis 等のプログラミングテクニックを、
備忘録的に記録しています。実際に動くソースコードを多用して説明していますので、
これからEclipseや、Spring-MVCを始めたいと思っている人にとって、少しでも参考になれば幸いです。
Spring-MVCの散歩道 > 応用の森(jQuery/JavaScript 編) > File APIを使用した、Ajaxファイルアップロードサンプル

package jp.dip.arimodoki.cntl;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import jp.dip.arimodoki.common.CConst;

@RestController
public class FileUploadAjax implements CConst {

    /**
     * Ajaxを使ったファイルアップロード処理
     * 初期画面を表示します
     * fileuploadajax.html
     */
    @RequestMapping(value = "/fileuploadajax")
     public ModelAndView fileuploadajax() {
        return new ModelAndView("fileuploadajax");
    }

    /**
     * Ajaxを使ったファイルアップロード処理
     * アップロード実行処理
     */
    @RequestMapping(value = "/uploadajax",
            method = RequestMethod.POST,
            //Response結果の全角が文字化けするのを防ぐおまじない
            produces = "text/html;charset=UTF-8"
    )
    public String uploadajax(
       //uploadfileで送信されたファイル情報を受け取りますが
       //これはサンプルなので、受け取ったファイル情報は放置で何もしません。
       @RequestParam("uploadfile") MultipartFile uploadfile
       ) throws Exception {

       //参考:@RequestParam("uploadfile") の"uploadfile" は、view側の
       //formData.append("uploadfile", file_data); で追加した時の左側の引数と同じ名前じゃないと
       //受け取れません。

        //Ajax呼び出し側に返却するJSON文字列を生成します。
        return "{\"status\":0,\"message\":\"Complete.\"}";
    }
}