ファイルダウンロード[非同期]
まずWEB-INFでフォルダdownloadを作成し、downloadフォルダの下にダウンロードされたファイルを入れ、HTTPアクセス時にControllerにファイル名を付けておけばよい.
例:.../download?fileName=jQuery.txt
フロントエンドJS部:
バックグラウンドコントローラ:
例:.../download?fileName=jQuery.txt
フロントエンドJS部:
<script type="text/javascript"> $(document).ready(function(){ $("#load").click(function(){ // , downLoad() , , downLoad('${pageContext.request.contextPath }/download/download','jQuery.txt'); }); }); /* JS : jQuary hidden , value , Controller, : fromAction: URL fileName: :fromAction:'${pageContext.request.contextPath }/download/download' fileName :'jQuery.txt' */ function downLoad(fromAction,fileName) { var form = $("<form>"); // form form.attr('style', 'display:none'); // form form.attr('target', ''); form.attr('method', 'post'); form.attr('action', fromAction+''); var input1 = $('<input>'); input1.attr('type', 'hidden'); input1.attr('name', 'fileName'); input1.attr('value', fileName+''); // $('body').append(form); // form.append(input1); form.submit(); } </script>
バックグラウンドコントローラ:
/** * @author 。 * @date 2016 3 7 * @Description: * @param: @param fileName * @return String null * @throws */
@RequestMapping("download")
public void download(String fileName, HttpServletRequest request,
HttpServletResponse response) {
response.setCharacterEncoding("utf-8");
response.setContentType("multipart/form-data");
response.setHeader("Content-Disposition", "attachment;fileName="
+ fileName);
try {
// /WEB-INF/download
String path = request.getSession().
getServletContext().getRealPath("/WEB-INF/download");
//
// File.separator(Windows '/')
InputStream inputStream = new FileInputStream(new File(path
+ File.separator + fileName));
OutputStream os = response.getOutputStream();
byte[] b = new byte[2048];
int length;
while ((length = inputStream.read(b)) > 0) {
os.write(b, 0, length);
}
//
os.close();
inputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}