<!-- jquery file upload相关js -->

<script src="/js/jquery-file-upload/js/jquery.ui.widget.js"></script>
<script src="/js/jquery-file-upload/js/jquery.iframe-transport.js"></script>
<script src="/js/jquery-file-upload/js/jquery.fileupload.js"></script>
<script src="/js/jquery-file-upload/js/jquery.fileupload-process.js"></script>
<script src="/js/jquery-file-upload/js/jquery.fileupload-validate.js"></script>
<link rel="stylesheet" href="/js/jquery-file-upload/css/jquery.fileupload.css">
<link rel="stylesheet" href="/js/jquery-file-upload/css/jquery.fileupload-ui.css">

$('#upload_cover').fileupload({
  url: '/img/upload',
  acceptFileTypes: /(\.|\/)(png)$/i,//文件后缀控制
  maxNumberOfFiles: 1,//最大上传文件数目
  maxFileSize: 50000,
  dataType: 'json',//期望从服务器得到json类型的返回数据
  messages : {//文件错误信息
  acceptFileTypes : '文件类型不匹配',
  maxFileSize : '文件过大',
  },processfail: function (e, data) {
    var currentFile = data.files[data.index];
    if (data.files.error && currentFile.error) {
      console.log(currentFile.error);
      $('#error').text(currentFile.error);
    }
  },
  done: function (e, data) {
    $('#imgUrl').val(data.result.fileUrl);
    $('#error').text("");
  },
  fail: function (e, data) {
    $('#error').text("上传失败!"+data.files.error);
  }
});

<!--html代码,样式使用bootstrap-->

<div class="form-group ">

  <label class="control-label col-lg-2"></label>

  <div class="col-sm-5">

    <span class="btn btn-success fileinput-button">选择<input type="file" id="upload_cover" /></span>

     <font color="red" id="error"></font><br/>
  </div>
</div>
<div class="form-group ">
  <label class="control-label col-lg-2">imgUrl<font color="red">*</font></label>
  <div class="col-lg-10">
    <input type="text" name="imgUrl" id="imgUrl" class="form-control" placeholder="请选择" value="" readonly="readonly"/>
  </div>
</div>

<!--服务端代码-->

@RequestMapping(value = "/img/upload", method = { RequestMethod.POST })
public void toUpload(HttpServletRequest request, HttpServletResponse response, ModelMap model) throws Exception {
  // 创建一个通用的多部分解析器
  CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
  // 新建目录
  String savePath = Constans.FILE_UPLOAD_PATH + Constans.IMG_FOLDER;
  File directory = new File(savePath);
  if (!directory.exists()) {
    directory.mkdirs();
  }
  try {
    // 判断 request 是否有文件上传,即多部分请求
    if (multipartResolver.isMultipart(request)) {
      // 转换成多部分request
      MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
      // 取得request中的所有文件名
      Iterator<String> iter = multiRequest.getFileNames();
      while (iter.hasNext()) {
        // 取得上传文件
        MultipartFile file = multiRequest.getFile(iter.next());
        if (file != null) {
          // 取得当前上传文件的文件名称
          String myFileName = file.getOriginalFilename();
          if (myFileName.trim() != "") {
            // 定义上传路径
            String tarpath = savePath + myFileName;
            File localFile = new File(tarpath);
            file.transferTo(localFile);
            model.addAttribute("fileUrl", tarpath);
            model.addAttribute("fileName", myFileName);
          }
        }

      }

    }
    logger.info(">>> upload complete");
  } catch (Exception e) {
    e.printStackTrace();
    logger.info(">>> upload error");
  } finally {
    response.setContentType("application/json; charset=utf-8");
    response.setCharacterEncoding("utf-8");
    PrintWriter pw = response.getWriter();
    pw.print(new Gson().toJson(model));
    pw.flush();
    pw.close();
  }

}

jquery file upload使用的更多相关文章

  1. jQuery File Upload 单页面多实例的实现

    jQuery File Upload 的 GitHub 地址:https://github.com/blueimp/jQuery-File-Upload 插件描述:jQuery File Upload ...

  2. jQuery File Upload done函数没有返回

    最近在使用jQuery File Upload 上传图片时发现一个问题,发现done函数没有callback,经过一番折腾,找到问题原因,是由于dataType: ‘json’造成的,改为autoUp ...

  3. 用jQuery File Upload做的上传控件demo,支持同页面多个上传按钮

    需求 有这么一个需求,一个form有多个文件要上传,但又不是传统的图片批量上传那种,是类似下图这种需求,一开始是用的swfupload做的上传,但是问题是如果有多个按钮的话,就要写很多重复的代码,于为 ...

  4. jquery file upload 文件上传插件

    1. jquery file upload 下载 jquery file upload Demo 地址:https://blueimp.github.io/jQuery-File-Upload/ jq ...

  5. jQuery File Upload跨域上传

    最近在做一个一手粮互联网项目,方案为前后端分离,自己负责前端框架,采用了Requirejs+avalonjs+jquery三个框架完成. 前后端通过跨域实现接口调用,中间也发现了不少问题,尤其是在富文 ...

  6. jquery ajax发送delete(use in jquery file upload delete file)

    环境: jQuery file upload HTML example code <div class="pic-preview"> <div class=&qu ...

  7. jquery file upload 后台收到的文件名中文乱码, filename中文乱码

    在jQuery File Upload.js文件里,在以下这个js中有个成员叫做 _initXHRData, 是一个function, 在这个function的最后部分有一个if-else分支,如下:

  8. jQuery File Upload

    jQuery File Upload介绍.............................................. 2 实现基本原理......................... ...

  9. jQuery File Upload 插件 php代码分析

    jquery file upload php代码分析首先进入构造方法 __construct() 再进入 initialize()因为我是post方式传的数据  在进入initialize()中的po ...

  10. jQuery File Upload blueimp with struts2 简单试用

    Official Site的话随便搜索就可以去了 另外新版PHP似乎都有问题  虽然图片都可以上传  但是response报错  我下载的是8.8.7木有问题   但是8.8.7版本结合修改main. ...

随机推荐

  1. .net core系列之《将.net core应用部署到Ubuntu》

    1.首先准备一个演示项目. 2.然后将这个项目用FileZilla工具上传到Ubuntu中. 3.进入目标文件,接下来有两种方法来部署项目 a.用dotnet run命令 root@hhz-virtu ...

  2. Python函数汇总(陆续更新中...)

    range的用法 函数原型:range(start, end, scan): 参数含义: start:计数从start开始.默认是从0开始.例如range(5)等价于range(0, 5); end: ...

  3. JavaScript停止事件冒泡和取消事件默认行为

    功能:停止事件冒泡 function stopBubble(e) { // 如果提供了事件对象,则这是一个非IE浏览器 if ( e && e.stopPropagation ) { ...

  4. [翻译] ABPadLockScreen

    ABPadLockScreen ABPadLockScreen aims to provide a universal solution to providing a secure keypad/pi ...

  5. [BZOJ 4555][Tjoi2016&Heoi2016]求和

    题意 给定 $n$ , 求下式的值: $$ f(n)= \sum_{i=0}^n\sum_{j=0}^i\begin{Bmatrix}i\\ j\end{Bmatrix}\times 2^j\time ...

  6. host 'xx' is not allowed to connect to this MySql server

    update mysql.user set host = '%' where user = 'root'; FLUSH PRIVILEGES; select * from mysql.user;

  7. spring mvc 多数据源切换,不支持事务控制[一]

    一个项目中需要使用两个数据库,Oracle 和Mysql ,于是参考各个blog,实现此功能.写好后才发现,原来的事务失效了,我去... spring-mybatis.xml 配置 <bean ...

  8. 2424. [HAOI2010]订货【费用流】

    Description 某公司估计市场在第i个月对某产品的需求量为Ui,已知在第i月该产品的订货单价为di,上个月月底未销完的单位产品要付存贮费用m,假定第一月月初的库存量为零,第n月月底的库存量也为 ...

  9. ValueError: Invalid leaf XXX

    Bug:ValueError: Invalid leaf XXX 无效的搜索条件——检查search函数中的domain表达式格式!是否少了括号! search(['user_id', '=', us ...

  10. EF和linq to sql 关系

    LINQ to SQL 允许你用任何类来代表数据库中的数据.表.同样的,EF也允许你用任何类来代表苏据库中的数据.表. 所不同的的地方是Linq to sql 用这些被修饰过的类直接同数据库打交道,存 ...