1.首先为html代码以及js代码

<div id="uploadDiv" style="display:none;"><!-- The fileinput-button span is used to style the file input field as button --><span class="btn btn-success fileinput-button"><i class="glyphicon glyphicon-plus"></i><span>文件选择</span><!-- The file input field used as target for the file upload widget --><input id="fileupload" type="file" name="file" ></span><button id="uploadBtn" class="btn btn-primary disabled" >确认上传</button><br><!-- The global progress bar --><div id="progress" class="progress"><div class="progress-bar progress-bar-success"></div></div><!-- The container for the uploaded files --><div id="msgDiv" class="files"></div></div>

$("#uploadBtn").click(function(){var dialog = $("#uploadDiv").clone().dialog({title: "附件上传",width : '75%',height : 500,modal : true});$('#fileupload', dialog).fileupload({dataType: 'json',progressall: function (e, data) {var progress = parseInt(data.loaded / data.total * 100, 10);$('#progress .progress-bar', dialog).css('width',progress + '%').html(progress + '%');$("#msgDiv", dialog).html("处理中……");},add: function (e, data) {data.url = "ra/suspiciousCase/uploadTotal";data.submit();$("#uploadBtn", dialog).off('click').on('click', function () {var id = getUrlParam('id');data.url = "ra/suspiciousCase/upload?id="+id;data.submit();setTimeout(function(){handleUploadTable();}, 3000);//延迟执行刷新
                });},done: function (e, data) {var isTotal = data.url.indexOf("uploadTotal") > -1;var tip = isTotal ? "解析成功,请点击“确认上传”" : "上传";var result = data.result;var msg = "<b>" + tip + "</b>"var bar = $('#progress .progress-bar');bar.removeClass("progress-bar-warning progress-bar-success");if(!result.success){msg = "<b>" + tip + "失败:</b>"+result.error;bar.addClass("progress-bar-warning");$("#uploadBtn", dialog).addClass("disabled");}else{bar.addClass("progress-bar-success");msg = "<b>" + tip + "成功:</b>";if(isTotal){$("#uploadBtn", dialog).removeClass("disabled");}}if(result.totalInfo){msg += "<br>";msg += "<b>提示信息:</b>" + result.totalInfo;}msg += "<br><b>文件名称:</b>" + data.files[0].name;$("#msgDiv", dialog).html(msg);}})})

再来是后台代码

@Path("/upload")@POST@NoCache@Consumes("multipart/form-data")public ExtJSResponse upload(@Context HttpServletRequest request) {ExtJSResponse resp = new ExtJSResponse(true);final String id = request.getParameter("id");final AmlSuspectcaseAttach attach = new AmlSuspectcaseAttach();boolean isMultipart= ServletFileUpload.isMultipartContent(request);  if(isMultipart){  //构造一个文件上传处理对象  FileItemFactory factory = new DiskFileItemFactory();  ServletFileUpload upload = new ServletFileUpload(factory);  @SuppressWarnings("rawtypes")Iterator items;  try{  checkPermission(Permissions.AML_SUSPECT_CASE);//解析表单中提交的所有文件内容  items = upload.parseRequest(request).iterator();  while(items.hasNext()){  FileItem item = (FileItem) items.next();  if(!item.isFormField()){  //取出上传文件的文件名称  String name = item.getName();  logger.info("上传文件的大小为:[{}]",item.getSize()); //取得上传文件以后的存储路径  final String suffix = name.substring(name.lastIndexOf('.') + 1, name.length());int fsize = fileSize*1024*1024;if(fileSuffix.contains(suffix)){if(item.getSize() < fsize){Long attachId = null;if(!StringUtils.isEmpty(name)){attach.setName(name);}if(!StringUtils.isEmpty(id)){attach.setCaseid(Long.parseLong(id));attachId = suspectCase.insertAttch(attach);System.out.println("attach:"+attachId);}if(resp.isSuccess()){//上传文件以后的存储路径
logger.info("上传文件:[{}]",attachId+"."+suffix);String Path= amlPath + File.separatorChar + attachId;  File file =new File(amlPath);//如果文件夹不存在则创建    if  (!file.exists()  && !file.isDirectory())      {file.mkdir();    } //上传文件  logger.info("上传文件的路径为:[{}]",Path);File uploaderFile = new File(Path);  item.write(uploaderFile);}}else{logger.info("上传文件大小不能超过2M");resp.setSuccess(false);resp.setErrorMsg("上传文件大小不能超过2M");}}else{logger.info("文件格式不正确,请选择doc、docx、xls、xlsx、png、gif、jpg、jpeg、bmp后缀文件!");resp.setSuccess(false);resp.setErrorMsg("文件格式不正确,请选择doc、docx、xls、xlsx、png、gif、jpg、jpeg、bmp后缀文件!");}}  }  }catch(Exception e){  e.printStackTrace();  resp.setSuccess(false);resp.setErrorMsg("文件上传失败");}  }return resp;}@Path("/uploadTotal")@POST@NoCache@Consumes("multipart/form-data")public ExtJSResponse uploadTotal(@Context HttpServletRequest request) {ExtJSResponse resp = new ExtJSResponse(true);@SuppressWarnings("unused")InputStream instream = null;try {checkPermission(Permissions.AML_SUSPECT_CASE);ServletFileUpload upload = new ServletFileUpload();FileItemIterator fileIterator = upload.getItemIterator(request);while (fileIterator.hasNext()) {FileItemStream item = fileIterator.next();if ("file".equals(item.getFieldName())){instream  = item.openStream();break;} }StringBuilder total = new StringBuilder();resp.put("totalInfo", total);} catch (Exception e) {getLogger().warn(e.getMessage(), e);resp.setSuccess(false);resp.setErrorMsg(e.getLocalizedMessage());}return resp;}

其中uploadTotal方法是在文件上传之前先对文件进行解析,下面贴上我的上传效果图,我这里是用的frame弹窗

解析完再点击确认上传之后就完成了。

转载于:https://www.cnblogs.com/hcp9/p/5607667.html

用jQuery实现文件的上传,后台为spring+mybatis相关推荐

  1. jquery 分片上传php,jquery 大文件分片上传插件 fcup.js

    软件介绍 fcup.js fcup 是一款支持大文件切片上传插件.该jquery插件使用简单,配置简单明了,支持上传类型指定,进度条查看上传进度.. 安装 直接下载源码,上传功能需要php环境,演示地 ...

  2. Antd多文件上传后台接收为null问题

    Antd多文件上传后台接收为null问题 在使用antd开发过程中,Upload组件的上传,一般是通过action配置后端接口地址,自动上传文件:但是当文件数量较多时,需要进行手动上传,但是手动上传后 ...

  3. JQuery专栏之十五————利用文件框控件file实现文件的上传

    15. 利用文件框控件file实现文件的上传. 文件上传的方法有很多,jQuery也有许多文件上传控件.本例采用最基本的HTML文件框(<input type='file')实现文件上传,不限制 ...

  4. js获取input file框(文件上传框)内容,上传后台

    直接复制,修改jquery为你的本地路径,本js可以把file选择的图片,转化为base64对象.无论是回显,还是转成图片,或者直接上传后台都是可以滴. <!DOCTYPE html> & ...

  5. jquery 分片上传php,php 大文件分片上传

    前端部分 上传 //上传控件 uploadBig('upload','zip,rar,7z,tar',{ id: '', type: 'upload_file', } ,(res)=>{ //t ...

  6. 使用jQuery OCUpload实现excel文件一键上传功能

    使用jQuery OCUpload实现excel文件一键上传功能 js代码 //为导入按钮,添加一键上传效果 $("#button-import").upload({action: ...

  7. jquery form java_springmvc利用jquery.form插件异步上传文件示例

    需要的下载文件: jQuery.form.js jquery.js commons-fileupload.jar commons-io.jar 示例图片 pom.xml commons-fileupl ...

  8. ajax ashx 请选择文件,ajax+jquery+ashx如何实现上传文件

    ajax+jquery+ashx如何实现上传文件 第一:建立Default.aspx页面 ajax图片上传 function upload(){ var path = document.getElem ...

  9. elementui 上传请求头_element-ui上传组件多个文件同时上传请求一次后台接口(前后端代码版)...

    记录时间 2020年10月27日 22点38分 前言 在使用element-ui上传组件上传多个文件时,出现多个文件对应着多个请求,比如你要上传3个文件,那么将请求3个后台接口,这样会无形之中增加了后 ...

最新文章

  1. IOS开发—Using UIGestureRecognizer with Swift Tutoria
  2. Dalvik VM进程系统(二):分析Zygote的启动过程
  3. mysql 排序 简介
  4. 【Java从0到架构师(1),Java中高级面试题总结(全面)
  5. leetcode-92-反转链表②
  6. 高可用的 MFS 文件分布式系统(Drdb+heartbeat+MFS )
  7. Cubieboard2 debian
  8. 关于技术的学习及批判
  9. AOP 实现请求参数打印
  10. linux tail 命令
  11. mysql 优化配置 大批量数据插入_MySQL数据库插入100w条数据要花多久?
  12. WinRAR压缩加密
  13. python colour-science 绘制CIE 1976色度图
  14. 电脑字体变成繁体中文怎么更改过来呢
  15. 详解JAVA对象实例化过程
  16. 来自GitHub的Python开源项目,100%可用的12306多功能抢票助手,切勿作为商业用途
  17. 一个纯粹的中文搜索引擎【Doge Doge】多吉搜索
  18. 如何搭建Telegram群机器人
  19. 【胖虎的逆向之路】如何绕过 Android11新特性之 “包的可见性“
  20. 东大22春《大学英语(四)》在线平时作业1_100分答案非答案

热门文章

  1. Linux/docker下oracle开启监听,开启自动启动
  2. 2022-2028年中国绿冻石行业市场研究及前瞻分析报告
  3. 2021-2027年中国透明熔融石英管行业市场全景调查及投资前景分析报告
  4. 2022-2028年中国大气污染防治产业投资分析及前景预测报告
  5. 如何kill同一个应用的所有进程
  6. django自带的分页功能
  7. 机房收费系统总结【5】——无用功
  8. torch.nn.functional.cross_entropy.ignore_index
  9. 用gensim学习word2vec
  10. TVM 高效保护隐私 ML