表單檔案上傳下載ajax方式返回值
阿新 • • 發佈:2019-01-06
頁面引入:jquery-form.js
function importSaleOrder(){
var file=$("#file").val();
if(file!=""){
$("#errorInfo").html("");
$("#downErrorFile").hide();
var form = $("form[id=importSaleOrderFrom]");
var options = {
url:ctx+'/warehouse-out/importBatchWhoutSaleOrder.jhtml' ,
type:'post',
success:function(data)
{
var fileName = data.filePath;
var errors = data.errors;
$("#errorInfo").html(errors);
$("#downErrorFile" ).show();
$("#downErrorFile").attr("href",ctx+'/warehouse-out/downloadExcel.jhtml?fileFileName='+fileName);
}
};
form.ajaxSubmit(options);
}else{
alert("請選擇檔案!");
}
}
下載:
public String downloadExcel(){
String realPath = ServletActionContext.getServletContext().getRealPath("/" )+"/upload";
File file = new File(realPath,fileFileName);
downloadExcel(file, response);
return null;
}
/**
* 報表檔案下載
* @param file
* @param response
*/
public void downloadExcel(File file, HttpServletResponse response) {
try {
// 取得檔名。
String filename = file.getName();
String userAgent = request.getHeader("USER-AGENT");
String finalFileName = null;
if(StringUtils.contains(userAgent, "MSIE")){//IE瀏覽器
finalFileName = URLEncoder.encode(filename,"UTF8");
}else if(StringUtils.contains(userAgent, "Mozilla")){//google,火狐瀏覽器
finalFileName = new String(filename.getBytes(), "ISO8859-1");
}else{
finalFileName = URLEncoder.encode(filename,"UTF8");//其他瀏覽器
}
// 以流的形式下載檔案。
InputStream fis = new BufferedInputStream(new FileInputStream(file));
byte[] buffer = new byte[fis.available()];
fis.read(buffer);
fis.close();
// 清空response
response.reset();
// 設定response的Header
response.addHeader("Content-Disposition", "attachment;filename="
+ finalFileName);
response.addHeader("Content-Length", "" + file.length());
OutputStream toClient = new BufferedOutputStream(
response.getOutputStream());
response.setContentType("application/vnd.ms-excel;charset=gb2312");
toClient.write(buffer);
toClient.flush();
toClient.close();
} catch (IOException ex) {
ex.printStackTrace();
}
if(file.exists()){
file.delete();
}
}
<form id="importSaleOrderFrom" action="${pageContext.request.contextPath}/warehouse-out/importBatchWhoutSaleOrder.jhtml" method="post" enctype="multipart/form-data">
<div class="col-md-7">
<div class="form-group">
<input id="file" type="file" name="file" onchange="clearForm()" >
</div>
<input type="button" value="匯入解析" onclick="importSaleOrder()" />
<label id="errorInfo" style="margin-left:20px;color: red;"></label>
<a href="#" style="display: none" id="downErrorFile" style="margin-left:40px;">下載檔案</a>
</div>
</form>