servlet 通過ajax上傳excel和引數
阿新 • • 發佈:2019-01-24
當時的引數是js裡獲取別的地方的,其實都一樣
jsp程式碼
<div id="uploadDlg" class="easyui-dialog" data-options="iconCls:'icon-upload',closed: true" style="width:300px;height:180px;padding:30px;display:none">
<form id="excel" method="post" enctype="multipart/form-data" >
<input type="file" name = "file" id="upExcel" style="width:240px">
</form>
</div>
js
function saveUpload() {
var upExcel = $("#upExcel").val();//這個是個很奇怪的值,但是可以獲取想要上傳的檔案結尾
if(upExcel == ''){
alert("請選擇excel,再上傳");
}else if(upExcel.lastIndexOf(".xls")<0){//可判斷以.xls和.xlsx結尾的excel
alert("只能上傳Excel檔案");
}else {
var formData = new FormData($("#excel")[0]);//表單id
var xhLxComb= $("#xhLxComb").combobox('getValue');
formData.append("xhLxComb",xhLxComb);//引數
//formData.append("file",document.getElementById("excel"));
$.ajax({
url: basePath + "/dataCollectServlet.do?action=uploadExcelSO2" ,
type: 'POST',
data: formData,
async: false,
cache: false,
contentType: false,
processData: false,
success: function (data) {
if(data == "1"){
$('#uploadDlg').dialog('close');//關閉補採視窗
$.messager.show({ //這裡其實就在在螢幕的右下角顯示一個提示框
title: '提示',
msg: '補採成功'
})
}else if(data == "0"){
$('#uploadDlg').dialog('close');//關閉補採視窗
$.messager.show({ //這裡其實就在在螢幕的右下角顯示一個提示框
title: '提示',
msg: '補採失敗,資料可能存在問題'
})
}
$("#dg").datagrid("reload"); //重新載入資料,即:重新整理頁面
}
});
}
}
Controller層
// 上傳配置
private static final int MEMORY_THRESHOLD = 1024 * 1024 * 3; // 3MB
private static final int MAX_FILE_SIZE = 1024 * 1024 * 40; // 40MB
private static final int MAX_REQUEST_SIZE = 1024 * 1024 * 50; // 50MB
/**
* 配置上傳引數
*/
private ServletFileUpload uploadSetting() {
// 配置上傳引數
DiskFileItemFactory factory = new DiskFileItemFactory();
// 設定記憶體臨界值 - 超過後將產生臨時檔案並存儲於臨時目錄中
factory.setSizeThreshold(MEMORY_THRESHOLD);
// 設定臨時儲存目錄
factory.setRepository(new File(System.getProperty("java.io.tmpdir")));
ServletFileUpload upload = new ServletFileUpload(factory);
// 設定最大檔案上傳值
upload.setFileSizeMax(MAX_FILE_SIZE);
// 設定最大請求值 (包含檔案和表單資料)
upload.setSizeMax(MAX_REQUEST_SIZE);
return upload;
}
private void uploadExcelSO2(HttpServletRequest request, HttpServletResponse response) throws IOException {
PrintWriter out = response.getWriter();
int ret = 0;
ServletFileUpload upload = uploadSetting();//配置上傳引數
List<RealTimeSO2> list = new LinkedList<RealTimeSO2>();
String xhLx = "";
try {
// 解析請求的內容提取檔案資料
@SuppressWarnings("unchecked")
List<FileItem> formItems = upload.parseRequest(request);
if (formItems != null && formItems.size() > 0) {
// 迭代表單資料
for (FileItem item : formItems) {
// 處理不在表單中的欄位
if (!item.isFormField()) {
list = this.dataCollectService.dealUploadExcel(item);//處理上傳的excel資料,如果是file檔案就處理file
continue;
} else {
xhLx = item.getString("UTF-8");
continue;
}
}
}
} catch (Exception ex) {
request.setAttribute("message", "錯誤資訊: " + ex.getMessage());
}
if (list == null || list.isEmpty()) {
ret = 0;
} else {
ret = this.dataCollectService.uploadExcel(list, xhLx);//service層處理接收的資料
}
out.print(ret);
out.flush();
out.close();
}
service層
public List<RealTimeSO2> dealUploadExcelSO2(FileItem item) throws IOException {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
Workbook wb = new HSSFWorkbook(item.getInputStream());
Sheet sheet = wb.getSheetAt(0);
int totalRows = sheet.getPhysicalNumberOfRows();// 得到Excel的行數
int totalCells = 0;
if (totalRows > 1 && sheet.getRow(1) != null) {
totalCells = 17;
}
List<RealTimeSO2> list = new LinkedList<RealTimeSO2>();
for (int r = 2; r < totalRows; r++) {
Row row = sheet.getRow(r);
if (row == null) {
break;
}
RealTimeSO2 realTimeSO2 = new RealTimeSO2();
// 迴圈Excel的列
for (int c = 0; c < totalCells; c++) {
Cell cell = row.getCell(c);
if (c == 0) {
if (cell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC) {
cell.setCellType(HSSFCell.CELL_TYPE_STRING);
realTimeSO2.setFacId(cell.getStringCellValue());// 廠站id
}
} else if (c == 1) {
if (cell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC) {
cell.setCellType(HSSFCell.CELL_TYPE_STRING);
realTimeSO2.setHouseId(cell.getStringCellValue());// 管道id
}
} else if (c == 2) {
if (cell.getCellType() == HSSFCell.CELL_TYPE_STRING) {
cell.setCellType(HSSFCell.CELL_TYPE_STRING);
realTimeSO2.setFacName(cell.getStringCellValue());// 廠站名字
}
}
}
list.add(realTimeSO2);
}
return list;
}