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插件HighCharts绘制简单2D折线图效果示例【附demo源码】
Mar 21 jQuery
基于jquery日历价格、库存等设置插件
Jul 05 jQuery
使用 jQuery 实现表单验证功能
Jul 05 jQuery
jQuery制作全屏宽度固定高度轮播图(实例讲解)
Jul 08 jQuery
jQuery结合jQuery.cookie.js插件实现换肤功能示例
Oct 14 jQuery
jQuery超简单遮罩层实现方法示例
Sep 06 jQuery
js/jquery遍历对象和数组的方法分析【forEach,map与each方法】
Feb 27 jQuery
jQuery实现消息弹出框效果
Dec 10 jQuery
jQuery单页面文字搜索插件jquery.fullsearch.js的使用方法
Feb 04 jQuery
jquery实现抽奖功能
Oct 22 jQuery
使用jQuery实现购物车
Oct 29 jQuery
jQuery实现动态向上滚动
Dec 21 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
破解.net程序(dll文件)编译和反编译方法
2013/01/31 PHP
php数组保存文本与文本反编成数组实例
2014/11/13 PHP
PHP中的闭包(匿名函数)浅析
2015/02/07 PHP
使用PHP实现微信摇一摇周边红包
2016/01/04 PHP
thinkphp框架无限级栏目的排序功能实现方法示例
2020/03/29 PHP
PHP 使用位运算实现四则运算的代码
2021/03/09 PHP
一些相见恨晚的 JavaScript 技巧
2010/04/25 Javascript
JavaScript prototype属性深入介绍
2012/11/27 Javascript
如何将网页表格内容导入excel
2014/02/18 Javascript
js调试系列 断点与动态调试[基础篇]
2014/06/18 Javascript
JavaScript中实现最高效的数组乱序方法
2014/10/11 Javascript
使用JS实现jQuery的addClass, removeClass, hasClass函数功能
2014/10/31 Javascript
html的DOM中Event对象onabort事件用法实例
2015/01/21 Javascript
JavaScript中的bold()方法使用详解
2015/06/08 Javascript
JS+CSS实现鼠标经过弹出一个DIV框完整实例(带缓冲动画渐变效果)
2016/03/25 Javascript
div实现自适应高度的textarea实现angular双向绑定
2017/01/08 Javascript
微信分享调用jssdk实例
2017/06/08 Javascript
微信小程序实现多个按钮toggle功能的实例
2017/06/13 Javascript
ionic2自定义cordova插件开发以及使用(Android)
2017/06/19 Javascript
Vue导出json数据到Excel电子表格的示例
2017/12/04 Javascript
jQuery操作元素追加内容示例
2020/01/10 jQuery
jQuery 移除事件的方法
2020/06/20 jQuery
JavaScript数组常用的增删改查与其他属性详解
2020/10/13 Javascript
用Nodejs实现在终端中炒股的实现
2020/10/18 NodeJs
Python如何获取系统iops示例代码
2016/09/06 Python
对python pandas 画移动平均线的方法详解
2018/11/28 Python
中国海淘族值得信赖的海淘返利网站:55海淘
2017/01/16 全球购物
Dillard’s百货官网:Dillards.com
2018/05/26 全球购物
介绍一下JNDI的基本概念
2013/07/26 面试题
公务员政审单位鉴定材料
2014/05/16 职场文书
银行求职自荐书
2014/06/25 职场文书
财务工作犯错检讨书
2014/10/07 职场文书
电影雷锋观后感
2015/06/10 职场文书
公司开业致辞
2015/07/29 职场文书
如何用JavaScript实现一个数组惰性求值库
2021/05/05 Javascript
vue Element-ui表格实现树形结构表格
2021/06/07 Vue.js