jQuery利用FormData上传文件实现批量上传


Posted in jQuery onDecember 04, 2018

在项目中涉及题库的批量上传功能,在此利用formdata进行文件上传,后台读取,进行批量插入。同时还需要带入teacherId和courseId两个参数,所以将文件和两个参数append到formdata中,传到后台。

jQuery利用FormData上传文件实现批量上传

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);

自此即可实现批量上传,需要注意的是,这里定义的文件类型为Part类型。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木,关注三水点靠木公众号的更多精彩内容。

jQuery 相关文章推荐
jQuery树插件zTree使用方法详解
May 02 jQuery
利用JQuery操作iframe父页面、子页面的元素和方法汇总
Sep 10 jQuery
jquery学习笔记之无new构建详解
Dec 07 jQuery
jQuery zTree搜索-关键字查询 递归无限层功能实现代码
Jan 25 jQuery
jQuery实现的电子时钟效果完整示例
Apr 28 jQuery
jQuery的Ajax接收java返回数据方法
Aug 11 jQuery
学习jQuery中的noConflict()用法
Sep 28 jQuery
jquery中为什么能用$操作
Jun 18 jQuery
JQuery事件委托(适用于给动态生成的脚本元素添加事件)
Feb 01 jQuery
jquery实现上传图片功能
Jun 29 jQuery
JQuery Ajax如何实现注册检测用户名
Sep 25 jQuery
jquery实现抽奖功能
Oct 22 jQuery
利用jquery和BootStrap实现动态滚动条效果
Dec 03 #jQuery
jQuery-ui插件sortable实现自由拖动排序
Dec 01 #jQuery
jquery拖拽自动排序插件使用方法详解
Jul 20 #jQuery
jQuery实现网页拼图游戏
Apr 22 #jQuery
基于jquery实现九宫格拼图小游戏
Nov 30 #jQuery
jQuery实现购物车的总价计算和总价传值功能
Nov 28 #jQuery
jQuery点击页面其他部分隐藏下拉菜单功能
Nov 27 #jQuery
You might like
PHP中的CMS的涵义
2007/03/11 PHP
php实现删除指定目录下相关文件的方法
2014/10/20 PHP
php最简单的删除目录与文件实现方法
2014/11/28 PHP
php+Ajax无刷新验证用户名操作实例详解
2019/03/04 PHP
Yii 使用intervention/image拓展实现图像处理功能
2019/06/22 PHP
PhpStorm+xdebug+postman调试技巧分享
2020/09/15 PHP
列表内容的选择
2006/06/30 Javascript
JQuery扩展插件Validate—4设置错误提示的样式
2011/09/05 Javascript
js创建数据共享接口——简化框架之间相互传值
2011/10/23 Javascript
jquery插件EasyUI中form表单提交实例分享
2016/01/11 Javascript
Nodejs如何搭建Web服务器
2016/03/28 NodeJs
Nodejs下DNS缓存问题浅析
2016/11/16 NodeJs
微信小程序模板之分页滑动栏
2017/02/10 Javascript
Angular.js指令学习中一些重要属性的用法教程
2017/05/24 Javascript
bootstrap模态框嵌套、tabindex属性、去除阴影的示例代码
2017/10/17 Javascript
利用three.js画一个3D立体的正方体示例代码
2017/11/19 Javascript
vue 组件 全局注册和局部注册的实现
2018/02/28 Javascript
Vuex入门到上手教程
2018/06/20 Javascript
vue data引入本地图片的两种方式小结
2019/11/13 Javascript
[00:11]战神迅矛
2019/03/06 DOTA
wxPython 入门教程
2008/10/07 Python
python赋值操作方法分享
2013/03/23 Python
通过Python实现自动填写调查问卷
2017/09/06 Python
解决python3 网络请求路径包含中文的问题
2018/05/10 Python
Python3中列表list合并的四种方法
2019/04/19 Python
python tkinter组件摆放方式详解
2019/09/16 Python
python更新数据库中某个字段的数据(方法详解)
2020/11/18 Python
python try...finally...的实现方法
2020/11/25 Python
介绍一下javax.servlet.Servlet接口及其主要方法
2015/11/30 面试题
给校长的建议书100字
2014/05/16 职场文书
贷款委托书怎么写
2014/08/02 职场文书
清明节网上祭英烈寄语2015
2015/03/04 职场文书
少儿励志名言(80句)
2019/08/14 职场文书
2019年感恩励志演讲稿(收藏备用)
2019/09/11 职场文书
Java 实战项目之家居购物商城系统详解流程
2021/11/11 Java/Android
Python绘画好看的星空图
2022/03/17 Python