jQuery利用FormData上傳文件實(shí)現(xiàn)批量上傳
在項(xiàng)目中涉及題庫(kù)的批量上傳功能,在此利用formdata進(jìn)行文件上傳,后臺(tái)讀取,進(jìn)行批量插入。同時(shí)還需要帶入teacherId和courseId兩個(gè)參數(shù),所以將文件和兩個(gè)參數(shù)append到formdata中,傳到后臺(tái)。

JQuery 函數(shù)的提交按鈕執(zhí)行的函數(shù)如下:
<script type="text/javascript">
//批量上傳題庫(kù)
function fileSubmit() {
var questionFile = new FormData();
var fileObj = document.getElementById("questionFile").files[0];
// js 獲取文件對(duì)象,questionFile為文件選擇框的Id
questionFile.append("file", fileObj);
var teacherId=localStorage.getItem("teacherId");
questionFile.append("teacherId",teacherId);
var courseId=localStorage.getItem("courseId");
questionFile.append("courseId",courseId);
$.ajax({
async: false,
type:"post",
url:"/questions/batchUpload",
data:questionFile,
processData : false, //必須false才會(huì)避開jQuery對(duì) formdata 的默認(rèn)處理
contentType : false, //必須false才會(huì)自動(dòng)加上正確的Content-Type
success:function (data) {
layer.msg("上傳成功");
example.ajax.reload();
}
});
}
</script>
需要注意的是以下兩點(diǎn):
- jQuery 的 ajax 中processData設(shè)置為false (表示不需要對(duì)數(shù)據(jù)做處理)
- jQuery 的 ajax 中contentType設(shè)置為false (因?yàn)榍懊嬉呀?jīng)聲明了是‘FormData對(duì)象')
Controller 中的方法如下:
@ApiOperation(value = "批量上傳題庫(kù)")
@RequestMapping(value = "/batchUpload",method = RequestMethod.POST)
public void batchUploadQuestions(HttpServletRequest request) throws Exception{
Collection<Part> files = request.getParts();
questionsService.batchUploadQuestions(files);
}
Service中的方法如下:
//題庫(kù)的批量上傳
@Override
public void batchUploadQuestions(Collection<Part> files) throws Exception {
Iterator<Part> it = files.iterator();
Part file = it.next();
Workbook workbook = null;
if (file.getSubmittedFileName().endsWith("xlsx")) {
workbook = new XSSFWorkbook(file.getInputStream());
} else if (file.getSubmittedFileName().endsWith("xls")) {
workbook = new HSSFWorkbook(file.getInputStream());
}
Cell cell = null;
List<Questions> questionsList = new ArrayList<>();
//判斷Excel中有幾張表,目前設(shè)定為一張表
Sheet sheet = workbook.getSheetAt(0);//獲取sheet表
for (int rowIndex = 2; rowIndex <= sheet.getLastRowNum(); rowIndex++) { //獲取到一行
Row row = sheet.getRow(rowIndex);
if (row == null) {
continue;
}
Questions questions = new Questions();
List<String> strList = new ArrayList<>();
for (int i = 1; i < row.getLastCellNum(); i++) {
//獲取到一列,第一列為序號(hào)不需要存入數(shù)據(jù)庫(kù),所以從1開始讀
cell = row.getCell(i);
String value = "";
switch (cell.getCellTypeEnum()) {
case _NONE:
break;
case STRING:
value = cell.getStringCellValue();
break;
case NUMERIC:
Pattern points_ptrn = Pattern.compile("0.0+_*[^/s]+");
if (DateUtil.isCellDateFormatted(cell)) {//日期
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
value = sdf.format(DateUtil.getJavaDate(cell.getNumericCellValue()));
} else if ("@".equals(cell.getCellStyle().getDataFormatString())
|| "General".equals(cell.getCellStyle().getDataFormatString())
|| "0_".equals(cell.getCellStyle().getDataFormatString())) {
//文本 or 常規(guī) or 整型數(shù)值
DecimalFormat df = new DecimalFormat("0");
value = df.format(cell.getNumericCellValue());
} else if (points_ptrn.matcher(cell.getCellStyle().getDataFormatString()).matches()) {//正則匹配小數(shù)類型
value = String.valueOf(cell.getNumericCellValue());//直接顯示
}
break;
default:
value = cell.toString();
}
if ((i == 2 || i == 3) && value.equals("")) {//此處設(shè)計(jì)不需要讀入的單元格
strList.clear();
break;
}
strList.add(value);
}
if (strList.size() == 9) {
//對(duì)應(yīng)數(shù)據(jù)庫(kù)屬性進(jìn)行存儲(chǔ)
questions.setChapter(strList.get(0));
questions.setSection(strList.get(1));
questions.setType(strList.get(2));
questions.setQuestion(strList.get(3));
questions.setAnswerA(strList.get(4));
questions.setAnswerB(strList.get(5));
questions.setAnswerC(strList.get(6));
questions.setAnswerD(strList.get(7));
questions.setAnswerTrue(strList.get(8));
questionsList.add(questions);
}
}
//將前臺(tái)存進(jìn)的teacherId也當(dāng)做文件進(jìn)行讀取
Part file1 = it.next();
InputStream inputStream = file1.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line = null;
String teacherId = "";
while ((line = bufferedReader.readLine()) != null) {
teacherId = line;
}
//將前臺(tái)傳入的courseId當(dāng)做文件讀取
Part file2 = it.next();
InputStream inputStream1 = file2.getInputStream();
BufferedReader bufferedReader1 = new BufferedReader(new InputStreamReader(inputStream1));
String line1 = null;
String courseId = "";
while ((line1 = bufferedReader1.readLine()) != null) {
courseId = line1;
}
batchSaveQuestionList(teacherId, courseId, questionsList);
}
//SQL 語(yǔ)句拼接后傳入DAO層進(jìn)行數(shù)據(jù)插入
public void batchSaveQuestionList(String teacherId,String courseId,List<Questions> questionsList){
String sql = "replace into questions(questionId,courseId,teacherId,chapter,section,type,question,answerA,answerB,answerC,answerD,answerTrue) values";
for(int i = 0;i<questionsList.size();i++){
String questionId = String.valueOf(System.currentTimeMillis())+i;
if(i==0){
sql+="('"+questionId+"','"+courseId+"','"+teacherId+"','"+questionsList.get(i).getChapter()+"','"+questionsList.get(i).getSection()
+ "','"+questionsList.get(i).getType()+"','"+questionsList.get(i).getQuestion()+ "','"+ questionsList.get(i).getAnswerA()
+"','"+questionsList.get(i).getAnswerB()+"','"+questionsList.get(i).getAnswerC()+"','"+questionsList.get(i).getAnswerD()
+"','"+questionsList.get(i).getAnswerTrue()+"')";
}else{
sql+=",('"+questionId+"','"+courseId+"','"+teacherId+"','"+questionsList.get(i).getChapter()+"','"+questionsList.get(i).getSection()
+ "','"+questionsList.get(i).getType()+"','"+questionsList.get(i).getQuestion()+ "','"+ questionsList.get(i).getAnswerA()
+"','"+questionsList.get(i).getAnswerB()+"','"+questionsList.get(i).getAnswerC()+"','"+questionsList.get(i).getAnswerD()
+"','"+questionsList.get(i).getAnswerTrue()+"')";
}
}
questionsDao.batchSaveQuestionList(sql);
}
DAO層的數(shù)據(jù)插入語(yǔ)句:
@Insert("${sql}")
void batchSaveQuestionList(@Param("sql") String sql);
自此即可實(shí)現(xiàn)批量上傳,需要注意的是,這里定義的文件類型為Part類型。
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家,關(guān)注腳本之家公眾號(hào)的更多精彩內(nèi)容。
相關(guān)文章
解決JQuery的ajax函數(shù)執(zhí)行失敗alert函數(shù)彈框一閃而過(guò)問(wèn)題
這篇文章主要介紹了解決JQuery的ajax函數(shù)執(zhí)行失敗alert函數(shù)彈框一閃而過(guò)問(wèn)題,非常不錯(cuò),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2019-04-04
jquery獲取焦點(diǎn)和失去焦點(diǎn)事件代碼
鼠標(biāo)在搜索框中點(diǎn)擊的時(shí)候里面的文字就消失了,經(jīng)常會(huì)用到搜索框的獲得焦點(diǎn)和失去焦點(diǎn)的事件,接下來(lái)介紹一下具體代碼,感興趣的朋友額可以參考下2013-04-04
基于jQuery實(shí)現(xiàn)仿51job城市選擇功能實(shí)例代碼
這篇文章主要介紹了基于jQuery實(shí)現(xiàn)仿51job城市選擇功能實(shí)例代碼的相關(guān)資料,需要的朋友可以參考下2016-03-03
基于jQuery實(shí)現(xiàn)發(fā)送短信驗(yàn)證碼后的倒計(jì)時(shí)功能(無(wú)視頁(yè)面關(guān)閉)
最近做了一個(gè)項(xiàng)目,其中有需求要求實(shí)現(xiàn)發(fā)送短信驗(yàn)證碼后倒計(jì)時(shí)功能,其中有個(gè)難點(diǎn):要求關(guān)閉頁(yè)面也進(jìn)行倒計(jì)時(shí)。好吧,下面小編把jquery 發(fā)送驗(yàn)證碼倒計(jì)時(shí)的實(shí)現(xiàn)代碼分享給大家,大家可以參考下2016-09-09
jquery模擬picker實(shí)現(xiàn)滑動(dòng)選擇效果
這篇文章主要為大家詳細(xì)介紹了jquery模擬picker實(shí)現(xiàn)滑動(dòng)選擇效果,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-04-04
javascript向后臺(tái)傳送相同屬性的參數(shù)即數(shù)組參數(shù)
在傳送參數(shù)時(shí),經(jīng)常會(huì)碰到向后臺(tái)傳送一些相同屬性的參數(shù),最好的選擇是采用數(shù)組的方式,下面有個(gè)不錯(cuò)的示例,大家可以參考下2014-02-02
Visual Studio中的jQuery智能提示設(shè)置方法
Visual Studio中的jQuery智能提示設(shè)置方法,喜歡用vs2008開發(fā)的朋友可以參考下。2010-03-03

