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轻松实现无缝轮播效果
Mar 22 jQuery
jquery中each循环的简单回滚操作
May 05 jQuery
jquery单击文字或图片内容放大并居中显示
Jun 23 jQuery
jQuery实现拼图小游戏(实例讲解)
Jul 24 jQuery
jQuery实现标签子元素的添加和赋值方法
Feb 24 jQuery
jQuery中的类名选择器(.class)用法简单示例
May 14 jQuery
jquery引入外部CDN 加载失败则引入本地jq库
May 23 jQuery
jQuery基于闭包实现的显示与隐藏div功能示例
Jun 09 jQuery
JQuery Ajax动态加载Table数据的实例讲解
Aug 09 jQuery
jQuery实现根据身份证号获取生日、年龄、性别等信息的方法
Jan 09 jQuery
JS/jQuery实现简单的开关灯效果【案例】
Feb 19 jQuery
Javascript和jquery在selenium的使用过程
Oct 31 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设计模式中的工厂模式
2008/06/12 PHP
PHP字符串函数系列之nl2br(),在字符串中的每个新行 (\n) 之前插入 HTML 换行符br
2011/11/10 PHP
php 计划任务 检测用户连接状态
2012/03/29 PHP
php获取$_POST同名参数数组的实现介绍
2013/06/30 PHP
利用浏览器的Javascript控制台调试PHP程序
2014/01/08 PHP
php菜单/评论数据递归分级算法的实现方法
2019/08/01 PHP
win10下 php安装seaslog扩展的详细步骤
2020/12/04 PHP
jQuery EasyUI API 中文文档 - Menu菜单
2011/10/03 Javascript
基于jquery的拖动布局插件
2011/11/25 Javascript
jQuery不间断滚动效果(模拟百度新闻支持文字/图片/垂直滚动)
2013/02/05 Javascript
JS获取浏览器版本及名称实现函数
2013/04/02 Javascript
JS图片根据鼠标滚动延时加载的实例代码
2013/07/13 Javascript
JS将秒换成时分秒实现代码
2013/09/03 Javascript
JS实现很酷的EMAIL地址添加功能实例
2015/02/28 Javascript
JS实现的最简Table选项卡效果
2015/10/14 Javascript
全面解析多种Bootstrap图片轮播效果
2016/05/27 Javascript
关于网页中的无缝滚动的js代码
2016/06/09 Javascript
NPM 安装cordova时警告:npm WARN deprecated minimatch@2.0.10: Please update to minimatch 3.0.2 or higher to
2016/12/20 Javascript
JS匹配日期和时间的正则表达式示例
2017/05/12 Javascript
基于Vue实现后台系统权限控制的示例代码
2017/08/29 Javascript
利用Decorator如何控制Koa路由详解
2018/06/26 Javascript
axios异步提交表单数据的几种方法
2019/08/11 Javascript
Vue3.0数据响应式原理详解
2019/10/09 Javascript
浅谈Vue SSR中的Bundle的具有使用
2019/11/21 Javascript
Node快速切换版本、版本回退(降级)、版本更新(升级)
2021/01/07 Javascript
js实现验证码干扰(静态)
2021/02/22 Javascript
[48:46]完美世界DOTA2联赛PWL S2 SZ vs FTD.C 第二场 11.19
2020/11/19 DOTA
python 生成目录树及显示文件大小的代码
2009/07/23 Python
python实现猜数字游戏
2020/03/25 Python
Python如何使用turtle库绘制图形
2020/02/26 Python
Python 虚拟环境工作原理解析
2020/12/24 Python
孤独星球出版物:Lonely Planet Publications
2018/03/17 全球购物
一份教室追逐打闹的检讨书
2014/09/27 职场文书
如何理解及使用Python闭包
2021/06/01 Python
mysql中varchar类型的日期进行比较、排序等操作的实现
2021/11/17 MySQL
收音机爱好者玩机13年,简评其使用过的19台收音机
2022/04/30 无线电