关于文件上传使用AJAX的例子

在后台 需要一个上传的工具类:

@Controller
@RequestMapping(value="/upload")
public class UploadUtil {

    @ResponseBody
    @RequestMapping(value="/upload.do")
    public String upload2(HttpServletRequest request, HttpServletResponse response) throws Exception{
        //创建一个通用的多部分解析器
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
        //判断request是否有文件需要上传
        if(multipartResolver.isMultipart(request)){
            //转换成多部分request
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)request;
            String pth = null;
            List<MultipartFile> fileList = multiRequest.getFiles("file");
            for (MultipartFile mf : fileList) {
                if(!mf.isEmpty()){
                    //取得当前上传文件的名称
                    String myFileName = mf.getOriginalFilename();
                    //如果名称不为"",说明该文件存在,否则说明文件不存在。
                    if(myFileName.trim()!=""){
                        System.out.println(myFileName);
                        //重命名上传后的文件
                        String filename = "upload"+mf.getOriginalFilename();
                        String type=filename.substring(filename.lastIndexOf(".")+1);
                        if(type.equals("jpg")||type.equals("png")){
                            Date date = new Date();
                            SimpleDateFormat format = new SimpleDateFormat("yyMMddHHmmss");
                            String da = format.format(date);
                            String newName = da+ getRandomString2(4) + "." + type;
                            //定义上传路劲
                            String path = request.getSession().getServletContext().getRealPath("/uploadImg");
                            String reelPath = path+"/"+newName;
                            pth="/uploadImg/"+newName;
                            File localFile = new File(path);
                            if (!localFile.exists()) {                                               // 判断文件夹是否存在,不存在则新建
                                localFile.mkdirs();
                            }
                            File realFile = new File(reelPath);
                            mf.transferTo(realFile);
                            return pth;
                        }else{
                            return "2";//文件类型只能是JPG、PNG
                        }

                    }else{
                        return "1";//文件不存在
                    }
                }
            }
            return null;
        }else{
            return "0";//没有文件需要上传
        }
    }

    public static String getRandomString2(int length){
        Random random=new Random();
        StringBuffer sb=new StringBuffer();
        for(int i=0;i<length;i++){
            int number=random.nextInt(3);
            long result=0;
            switch(number){
                case 0:
                    result=Math.round(Math.random()*25+65);
                    sb.append(String.valueOf((char)result));
                    break;
                case 1:
                    result=Math.round(Math.random()*25+97);
                    sb.append(String.valueOf((char)result));
                    break;
                case 2:
                    sb.append(String.valueOf(new Random().nextInt(10)));
                    break;
            }

        }
        return sb.toString();
    }

}


在JSP页面上

<form id="imgForm" enctype="multipart/form-data" >
    <div class="form-group">
        <div style="display: inline-block"><label for="upfile">上传阶段图片:</label></div>
	<img id="preview" src="${ctx}/weixin/images/upload/upload_img.png">
<div style="display: inline-block"><input type="file" name="file" id="upfile" multiple="multiple"/></div> <div style="text-align: center; margin: 10px 0"><button id="setImg" type="button" class="btn btn-primary" >开始上传</button></div> </div></form>

最后一个AJAX的脚本


//上传图片
$("#wrapper").on("click", "#setImg",
    function() {
        var $file = $("#upfile");
        var fileObj = $file[0];
        var windowURL = window.URL || window.webkitURL;
        var dataURL;
        var $img = $("#preview");
        if (fileObj && fileObj.files && fileObj.files[0]) {
            dataURL = windowURL.createObjectURL(fileObj.files[0]);
            $img.css("width", "100%");
            $img.css("height", "100%");
            $img.attr('src', dataURL);
            var formData = new FormData($("#imgForm")[0]);
            $.ajax({
                url: "/agrovideo/upload/upload.do",
                type: 'post',
                data: formData,
                cache: false,
                processData: false,
                contentType: false,
                success: function(data) {
                    if (data != null && data != '') {
                        if (data == "0") {
                            $.MsgBox.Alert("没有文件需要上传");
                        } else if (data == "1") {
                            $.MsgBox.Alert("文件不存在");
                        } else if (data == "2") {
                            $.MsgBox.Alert("文件类型只能是JPG、PNG");
                        } else {
                            $.MsgBox.Alert("上传成功");
                            $("#imgPath").val(data);
                        }
                    } else {
                        $.MsgBox.Alert("上传失败");
                    }
                },
                error: function() {
                    $.MsgBox.Alert("上传失败");
                }
            });
        }
    });

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值