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插件之validation插件
Mar 29 jQuery
jQuery EasyUI的TreeGrid查询功能实现方法
Aug 08 jQuery
jQuery判断网页是否已经滚动到浏览器底部的实现方法
Oct 27 jQuery
jquery 输入框查找关键字并提亮颜色的实例代码
Jan 23 jQuery
jQuery发请求传输中文参数乱码问题的解决方案
May 22 jQuery
深入浅析angular和vue还有jquery的区别
Aug 13 jQuery
jQuery实现鼠标移到某个对象时弹出显示层功能
Aug 23 jQuery
详解jQuery获取特殊属性的值以及设置内容
Nov 14 jQuery
jQuery实现网页拼图游戏
Apr 22 jQuery
js/jQuery实现全选效果
Jun 17 jQuery
jQuery实现的移动端图片缩放功能组件示例
May 01 jQuery
JavaScript枚举选择jquery插件代码实例
Nov 17 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中的多态性[译]
2011/08/02 PHP
php正则表达式(regar expression)
2011/09/10 PHP
php curl模拟post请求小实例
2013/11/13 PHP
thinkphp3.2.2前后台公用类架构问题分析
2014/11/25 PHP
php简单实现多语言切换的方法
2016/05/09 PHP
Javascript MD4
2006/12/20 Javascript
JS测试显示屏分辨率以及屏幕尺寸的方法
2013/11/22 Javascript
js实现类似于add(1)(2)(3)调用方式的方法
2015/03/04 Javascript
深入浅析JavaScript面向对象和原型函数
2016/02/06 Javascript
jQuery Ajax 异步加载显示等待效果代码分享
2016/08/01 Javascript
JQuery动态添加Select的Option元素实现方法
2016/08/29 Javascript
Vue-cli 使用json server在本地模拟请求数据的示例代码
2017/11/02 Javascript
利用ECharts.js画K线图的方法示例
2018/01/10 Javascript
jQuery幻灯片插件owlcarousel参数说明中文文档
2018/02/27 jQuery
vue2.0+vue-router构建一个简单的列表页的示例代码
2019/02/13 Javascript
vue-cli配置flexible过程详解
2019/07/04 Javascript
Python内置的字符串处理函数整理
2013/01/29 Python
Python getopt模块处理命令行选项实例
2014/05/13 Python
Python随机生成一个6位的验证码代码分享
2015/03/24 Python
Python文件右键找不到IDLE打开项解决办法
2015/06/08 Python
Python虚拟环境virtualenv的安装与使用详解
2017/05/28 Python
python中模块查找的原理与方法详解
2017/08/11 Python
Python随机生成均匀分布在单位圆内的点代码示例
2017/11/13 Python
python3+selenium实现qq邮箱登陆并发送邮件功能
2019/01/23 Python
python删除文件夹下相同文件和无法打开的图片
2019/07/16 Python
python是否适合网页编程详解
2019/10/04 Python
将matplotlib绘图嵌入pyqt的方法示例
2020/01/08 Python
解决Keras TensorFlow 混编中 trainable=False设置无效问题
2020/06/28 Python
CSS3 3D酷炫立方体变换动画的实现
2019/03/26 HTML / CSS
Debenhams爱尔兰:英国知名的百货公司
2017/01/02 全球购物
里程积分管理买卖交换平台:Points.com
2017/01/13 全球购物
DogBuddy荷兰:找到你最完美的狗保姆
2019/04/17 全球购物
11月升旗仪式讲话稿
2014/02/15 职场文书
教师节活动总结
2014/08/29 职场文书
国家机关领导干部民主生活会对照检查材料思想汇报
2014/09/17 职场文书
毕业生自荐材料范文
2014/12/30 职场文书