jQuery插件之ajaxFileUpload异步上传

jQuery插件之ajaxFileUpload异步上传

介绍

  AjaxFileUpload.js 是一个异步上传文件的jQuery插件,原理是创建隐藏的表单和iframe然后用JS去提交,获得返回值。

  下载地址:

属性

语法:$.ajaxFileUpload([options])
url上传处理程序地址。
fileElementId需要上传的文件域的ID,即<input type="file">的ID。
secureuri是否启用安全提交,默认为false。 
dataType服务器返回的数据类型。可以为xml,script,json,html。如果不填写,jQuery会自动判断。
success提交成功后自动执行的处理函数,参数data就是服务器返回的数据。
error提交失败自动执行的处理函数。
data自定义参数。这个东西比较有用,当有数据是与上传的图片相关的时候,这个东西就要用到了。
type当要提交自定义参数时,这个参数要设置成post

错误提示

SyntaxError: missing ; before statement如果出现这个错误就需要检查url路径是否可以访问
SyntaxError: syntax error如果出现这个错误就需要检查处理提交操作的服务器后台处理程序是否存在语法错误
SyntaxError: invalid property id如果出现这个错误就需要检查文本域属性ID是否存在
SyntaxError: missing } in XML expression如果出现这个错误就需要检查文件name是否一致或不存在
Object function (a,b){return new e.fn.init(a,b,h)} has no method 'handleError'(谷歌浏览器)dataType参数一定要大写。如:dataType: 'HTML'
jQuery.handleError is not a functionhttp://zhangzhaoaaa.iteye.com/blog/2123021
其它自定义错误大家可使用变量$error直接打印的方法检查各参数是否正确,比起上面这些无效的错误提示还是方便很多

 例子

  脚本:

复制代码

<script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery.js"></script>
<script type="text/javascript" src="${pageContext.request.contextPath}/js/ajaxfileupload.js"></script>
<script>
/**
 * 异步上传图片
 */
    $(function () {
        $("#saveImg").click(function () {
                //效验上传图片类型
                var ths=$('#fileImg');
                if (ths.val().length <= 0) {
                    alert("请上传图片");
                    return false;
                } else if(!/\.(gif|jpg|jpeg|png|GIF|JPG|PNG)$/.test(ths.val())){
                    alert("图片类型必须是.gif,jpeg,jpg,png中的一种");
                    ths.val("");
                    return false;
                }
                //效验成功调用异步上传函数
                ajaxFileUpload();
                return true;
        })
    })
/**
 * ajaxFileUpload    JQuery异步上传插件
 */
    function ajaxFileUpload() {
        $.ajaxFileUpload
        (
            {
                url: realPath+"/whiteListRule/saveImg.htm", //用于文件上传的服务器端请求地址
                type: 'post',
                data: { gameId: gameId },
                secureuri: false, //是否需要安全协议,一般设置为false
                fileElementId: 'fileImg', //文件上传域的ID
                dataType: 'text', //返回值类型 一般设置为json
                success: function (data, status)  //服务器成功响应处理函数
                {
                    var data=eval("("+data+")")
                    if (typeof (data.error) != 'undefined') {
                        if (data.error != '') {
                            alert(data.error);
                        } else {
                            alert(data.msg);
                            $("#img1").attr("src", data.imgurl);
                        }
                    }
                },
                error: function (data, status, e)//服务器响应失败处理函数
                {
                    alert(e);
                }
            }
        )
        return false;
}
</script>

复制代码

  控制器:

复制代码

package com.shiliu.game.controller;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.shiliu.game.common.Constant;
import com.shiliu.game.domain.Game;
import com.shiliu.game.service.IGameService;
import com.shiliu.game.utils.PropertyUtil;
import com.shiliu.game.utils.ReadProperties;

/**
 * 异步上传控制器
 * @author wkr
 * @Date 2016-12-12
 *
 */
@Controller
@RequestMapping(value = "/whiteListRule")
public class WhiteListRuleController {

    //log4j
    private Logger log =Logger.getLogger(AddCustomerDataController.class);
    
    //存储图片路径
    private String fileUploadPath = PropertyUtil.getProperty("file_upload");
    
    //读取图片路径
    private String fileReadPath = PropertyUtil.getProperty("file_url");
    
    @Resource
    private IGameService gameService;            //Game
    
    /**
     * 上传图片
     * @param gameId    参数
     * @param multipart    文件
     * @param request
     * @return
     */
    @RequestMapping(value="/saveImg")
    @ResponseBody
    public String saveImgMethod(
        @RequestParam(value = "gameId") String gameId,
        @RequestParam(value="fileImg") MultipartFile multipart,
        HttpServletRequest request
    ){
        String path = null;
        File upload = null;                //已经保存文件的全路径
        String img = null;                //存储数据库路径
        String readPath = null;                //读取路径
        
        //返回信息
        String msg = "";
        String error = "";
        
        try {
            //存储路径
            path = fileUploadPath + Constant.FILE_PATH;
            
            //存储本地文件夹
            upload = ReadProperties.upload(multipart, path);
            
            //存储数据库路径
            img = Constant.FILE_PATH + "/" + upload.getName();
            
            //读取路径
            readPath = fileReadPath + Constant.FILE_PATH + "/" + upload.getName();
            
            //限制图片大小
            int ruleHeight = 400;
            int ruleWidth = 750;
            int deviation = 100;//误差
            
            BufferedImage sourceImg = ImageIO.read(new FileInputStream(upload));
            int imgHeight = sourceImg.getHeight();//图片高
            int imgWidth = sourceImg.getWidth();//图片宽
            
            if (Math.abs(ruleWidth - imgWidth) <= deviation && Math.abs(ruleHeight - imgHeight) <= deviation) {
                gameService.updateByPrimaryKeySelective(new Game(gameId, img));
                msg = "上传成功!";
            }else {
                error = "图片不符合规定误!";
            }
            
        } catch (Exception e) {
            error = "文件保存本地失败!";
            log.error("文件保存本地失败!", e);
        }
        
        String res = "{ error:'" + error + "', msg:'" + msg + "',imgurl:'" + readPath + "'}";
        return res;
    }
}

复制代码

  JSP:

复制代码

         <body>
            <!-- 异步上传图片 -->
            <b>背景图片(建议图片大小750&Chi;400,允许误差100已内)</b>
            <br>
                <img id="img1" alt="上传成功后显示图片" src="${fileUrl }${game.imageUrl1}">
            <br>
                <input id="fileImg" type="file" name="fileImg" size="80" />
                <input id="saveImg" type="button" value="上传图片"  />
        </body>

复制代码

如果前端采用的是jersey框架,需要加

@consumes(mediatype.MULTIPART_FORM_DATA)

@Produces(MediaType.APPLICATION_JSON)

接受采用FormDataMultiPart form对象来接受图片

原理分析

 ajaxfileupload.js

 $.ajaxFileUpload([options])

该文章来源于https://www.cnblogs.com/wkrbky/p/6228779.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值