您好,登錄后才能下訂單哦!
這篇文章將為大家詳細講解有關怎么在jQuery中使用FormData上傳文件,文章內容質量較高,因此小編分享給大家做個參考,希望大家閱讀完這篇文章后對相關知識有一定的了解。
jquery是一個簡潔而快速的JavaScript庫,它具有獨特的鏈式語法和短小清晰的多功能接口、高效靈活的css選擇器,并且可對CSS選擇器進行擴展、擁有便捷的插件擴展機制和豐富的插件,是繼Prototype之后又一個優秀的JavaScript代碼庫,能夠用于簡化事件處理、HTML文檔遍歷、Ajax交互和動畫,以便快速開發網站。
JQuery 函數的提交按鈕執行的函數如下:
<script type="text/javascript"> //批量上傳題庫 function fileSubmit() { var questionFile = new FormData(); var fileObj = document.getElementById("questionFile").files[0]; // js 獲取文件對象,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才會避開jQuery對 formdata 的默認處理 contentType : false, //必須false才會自動加上正確的Content-Type success:function (data) { layer.msg("上傳成功"); example.ajax.reload(); } }); } </script>
需要注意的是以下兩點:
jQuery 的 ajax 中processData設置為false (表示不需要對數據做處理)
jQuery 的 ajax 中contentType設置為false (因為前面已經聲明了是‘FormData對象')
Controller 中的方法如下:
@ApiOperation(value = "批量上傳題庫") @RequestMapping(value = "/batchUpload",method = RequestMethod.POST) public void batchUploadQuestions(HttpServletRequest request) throws Exception{ Collection<Part> files = request.getParts(); questionsService.batchUploadQuestions(files); }
Service中的方法如下:
//題庫的批量上傳 @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中有幾張表,目前設定為一張表 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++) { //獲取到一列,第一列為序號不需要存入數據庫,所以從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 常規 or 整型數值 DecimalFormat df = new DecimalFormat("0"); value = df.format(cell.getNumericCellValue()); } else if (points_ptrn.matcher(cell.getCellStyle().getDataFormatString()).matches()) {//正則匹配小數類型 value = String.valueOf(cell.getNumericCellValue());//直接顯示 } break; default: value = cell.toString(); } if ((i == 2 || i == 3) && value.equals("")) {//此處設計不需要讀入的單元格 strList.clear(); break; } strList.add(value); } if (strList.size() == 9) { //對應數據庫屬性進行存儲 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); } } //將前臺存進的teacherId也當做文件進行讀取 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; } //將前臺傳入的courseId當做文件讀取 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 語句拼接后傳入DAO層進行數據插入 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層的數據插入語句:
@Insert("${sql}") void batchSaveQuestionList(@Param("sql") String sql);
關于怎么在jQuery中使用FormData上傳文件就分享到這里了,希望以上內容可以對大家有一定的幫助,可以學到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。