使用spring mvc 下載文件

話不多說,直接上代碼:

@RequestMapping(value = "regList")
public ResponseEntity<byte[]> export() {
	HttpHeaders headers = new HttpHeaders();
	headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
	try {
	    //如果下載的文件名爲中文則需要這樣處理
	    headers.setContentDispositionFormData("attachment", new String("中文文件名.txt".getBytes("gbk"),"iso-8859-1"));
	} catch (UnsupportedEncodingException e) {
	    e.printStackTrace();
	}
	//網上有些人把HttpStatus.OK改成了HttpStatus.CREATED,這樣在IE下會有問題,無法下載文件。
	return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file), headers, HttpStatus.OK);
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章