欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2022-06-15 18:10:34
在项目中涉及题库的批量上传功能,在此利用formdata进行文件上传,后台读取,进行批量插入。同时还需要带入teacherid和courseid两个参数,所以将文件和两个参...

在项目中涉及题库的批量上传功能,在此利用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类型。

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