ssm+easyui+ajax异步图片上传

(1)在springmvc中配置

<!-- 文件上传 -->
    <bean id="multipartResolver" 
        class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!-- 上传文件大小限制 -->
        <property name="maxUploadSize">  
            <value>10485760</value>  
        </property>  
        <!-- 请求的编码格式, 和 jsp 页面一致 -->
        <property name="defaultEncoding">
            <value>UTF-8</value>
        </property>
    </bean>

(2)jsp页面如下:

  <form id="add-form" method="post" >
            <table cellpadding="5">

 <tr>
                    <td>新闻封面:</td>
                    <td>
                        <input class="wu-text easyui-textbox easyui-validatebox" type="text" id="add-photo" name="photo" readonly="readonly" value="/web-new/resources/upload/demo.jpg" data-options="required:true,missingMessage:'请上传封面'"></input>
                        <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-upload" onclick="uploadPhoto()">上传</a>
                        <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-eye" onclick="preview()">预览</a>
                    </td>
   </tr>

</table>

</form>

<div id="preview-dialog" class="easyui-dialog" data-options="closed:true,iconCls:'icon-save'" style="width:330px; padding:10px;">
        <table>
            <tr>
                <td><img id="preview-photo" src="/web-new/resources/upload/demo.jpg" width="300px"></td>
            </tr>
        </table>
</div>
<!-- 上传图片进度条 -->
<div id="process-dialog" class="easyui-dialog" data-options="closed:true,iconCls:'icon-upload',title:'正在上传图片'" style="width:450px; padding:10px;">
    <div id="p" class="easyui-progressbar" style="width:400px;" data-options="text:'正在上传中...'"></div>
</div>
<input type="file" id="photo-file" style="display:none;" onchange="upload()">

script脚本

 //弹出文件选择器
function uploadPhoto(){
    $("#photo-file").click();
    
}

//ajax上传图片

function upload(){
    if($("#photo-file").val() == '')return;
    var formData = new FormData();
    formData.append('photo',document.getElementById('photo-file').files[0]);
    $("#process-dialog").dialog('open');
    var interval = setInterval(start,200);
    $.ajax({
        url:'upload_photo.action',
        type:'post',
        data:formData,
        contentType:false,
        processData:false,
        success:function(data){
            clearInterval(interval);
            $("#process-dialog").dialog('close');
            if(data.type == 'success'){
                $("#preview-photo").attr('src',data.filepath);
                $("#add-photo").val(data.filepath);
            }else{
                $.messager.alert("消息提醒",data.msg,"warning");
            }
        },
        error:function(data){
            clearInterval(interval);
            $("#process-dialog").dialog('close');
            $.messager.alert("消息提醒","上传失败!","warning");
        }
    });
}

//打开预览窗口

function preview(){
    $('#preview-dialog').dialog({
        closed: false,
        modal:true,
        title: "预览封面图片",
        buttons: [{
            text: '关闭',
            iconCls: 'icon-cancel',
            handler: function () {
                $('#preview-dialog').dialog('close');                    
            }
        }],
        onBeforeOpen:function(){
            //$("#add-form input").val('');
        }
    });
}

//图片上传进度条的设置(可参考easyui的文档)
function start(){
        var value = $('#p').progressbar('getValue');
        if (value < 100){
            value += Math.floor(Math.random() * 10);
            $('#p').progressbar('setValue', value);
        }else{
            $('#p').progressbar('setValue',0)
        }
};

 controller

/**
     * 上传图片
     * @param photo
     * @param request
     * @return
     */
    @RequestMapping(value="/upload_photo",method=RequestMethod.POST)
    @ResponseBody
    public Map<String, String> uploadPhoto(MultipartFile photo,HttpServletRequest request){
        Map<String, String> ret = new HashMap<String, String>();
        if(photo == null){
            ret.put("type", "error");
            ret.put("msg", "选择要上传的文件!");
            return ret;
        }
        if(photo.getSize() > 10*1024*1024){
            ret.put("type", "error");
            ret.put("msg", "文件大小不能超过10M!");
            return ret;
        }
        //获取文件后缀
        String suffix = photo.getOriginalFilename().substring(photo.getOriginalFilename().lastIndexOf(".")+1,photo.getOriginalFilename().length());
        if(!"jpg,jpeg,gif,png".toUpperCase().contains(suffix.toUpperCase())){
            ret.put("type", "error");
            ret.put("msg", "请选择jpg,jpeg,gif,png格式的图片!");
            return ret;
        }
        String savePath = request.getServletContext().getRealPath("/") + "/resources/upload/";
        File savePathFile = new File(savePath);
        if(!savePathFile.exists()){
            //若不存在改目录,则创建目录
            savePathFile.mkdir();
        }
        String filename = new Date().getTime()+"."+suffix;
        try {
            //将文件保存至指定目录
            photo.transferTo(new File(savePath+filename));
        }catch (Exception e) {
            // TODO Auto-generated catch block
            ret.put("type", "error");
            ret.put("msg", "保存文件异常!");
            e.printStackTrace();
            return ret;
        }
        ret.put("type", "success");
        ret.put("msg", "用户上传图片成功!");
        ret.put("filepath",request.getServletContext().getContextPath() + "/resources/upload/" + filename );
        return ret;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_35449051/article/details/86767593