记录一次使用form表单完成图片上传功能(兼容ie9)

1.前台页面

<div class="dform_con" style="position: relative;" id="uploadform">
    <iframe id="file_upload_return" style="display: none" name="file_upload_return"></iframe>
    <form id="myForm" action="/sns/student/studentInfo_doUploadPhoto.action" target="file_upload_return" method="post" enctype="multipart/form-data">
        <a href="javascript:;" id="button" onclick="selectFile()" style="position:relative; z-index: 100;" class="btn_sm">上传证件照</a><p id="fileName" style="margin-left: 120px;margin-top: -40px;display:none"></p>
        <input onchange="showPic(this)" style=" position:absolute;top:10px; left:155px;z-index:99; display:none;"  type="file" id="imageUrls" name="photoPath" class="hidden" value="" accept="image/gif,image/jpeg,image/jpg,image/png"/>
        <img id="pic" src="" alt="" width="80px" height="50px"/>
        <span style="display: none;" id="isImage" >${(peTrainee.photoLink)!""}</span>
        <p class="dform_con_txt">证件照要求:大小不超过100MB,尺寸为2.5cm*3.5cm</p>
    </form>
</div>

2.JS

//上传图片
function uploadFile(){
        document.getElementById("myForm").submit();
        $("#file_upload_return").load(function(){//获取iframe中的内容
            var body = $(window.frames['file_upload_return'].document.body);
            var datas = eval('(' + body[0].textContent + ')');
            //console.log(data["photoLink"]);
            if(datas["photoLink"] !=null){
                data["peTrainee.photoLink"] = datas["photoLink"] ;
                saveOrUpdateUserInfo();
            }else{
                showTip("", result.message);
                return;
            }
        });
}
//图片回显 兼容ie9
function showPic(file) {
    var prevDiv = document.getElementById('pic');
    if (file.files && file.files[0]) {
        var reader = new FileReader();
        reader.onload = function(evt) {
            prevDiv.src = evt.target.result
        }
        reader.readAsDataURL(file.files[0]);
    } else {
        prevDiv.src = file.value
        //prevDiv.innerHTML = '<div class="img" style="filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale,src=\'' + file.value + '\'"></div>';
    }
}

3.后台代码

public String doUploadPhoto(){
        Map<String, Object> jsonMap = new HashMap<String, Object>();
        HttpServletRequest request = ServletActionContext.getRequest();
        jsonMap.put("success",false);
        HttpSession session=ServletActionContext.getRequest().getSession();
        UserSession userSession = null;
        Object obj=session.getAttribute(UserSession.ANALOG_USER_SESSION_KEY);
        if(obj!=null) {
            userSession=(UserSession)obj;
        } else {
            userSession = (UserSession) session.getAttribute(UserSession.USER_SESSION_KEY);
        }
        if(userSession==null||userSession.getSsoUser()==null){
            jsonMap.put("errorMessage", "请登录");
            return ajaxJson(jsonMap);
        }
        String photoLink = null; // 文件上传目录
        String fileName = this.getPhotoFileName();
        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload sfu = new ServletFileUpload(factory);
        try {
            List items = sfu.parseRequest(request);//从request得到所有上传域的列表
            Iterator<FileItem> i = items.iterator();
            while (i.hasNext()) {
                FileItem fileitem =(FileItem) i.next();
                String filename = fileitem.getName();
                if(!fileitem.isFormField()&&fileitem!=null){//判读不是普通表单域即是file
                    int index = filename.lastIndexOf(".");
                    String filtyp = filename.substring(index + 1, filename.length());
                    photoLink = Const.FILE_PATH + userSession.getId() + "." + filtyp; //整个路径加文件名
                    File fullFile = new File(new String(fileitem.getName().getBytes(), "utf-8")); // 解决文件名乱码问题
                    File savedFile = new File(ServletActionContext.getServletContext().getRealPath(Const.FILE_PATH) + "/" + userSession.getId()
                            + "." + filtyp);
                    fileitem.write(savedFile);
                    jsonMap.put("success",true);
                    jsonMap.put("photoLink",photoLink);
                    request.setAttribute("photoLink",photoLink);
                }
            }
        }catch(Exception e){
                e.printStackTrace();
                jsonMap.put("errorMessage", "照片上传失败!"+e.getMessage());
                jsonMap.put("message","照片上传失败!"+e.getMessage());
                logger.error("图片类型错误", e);
            }

        return ajaxJson(jsonMap);
    }
    //map转成json
    public String ajaxJson(Map<String, Object> jsonMap) {
        JSONObject jsonObject = JSONObject.fromObject(jsonMap);
        return ajax(jsonObject.toString(), "application/json");
    }

    // AJAX输出,返回null
    public String ajax(String content, String type) {
        try {
            HttpServletResponse response = ServletActionContext.getResponse();
            response.setContentType(type + ";charset=UTF-8");
            response.setHeader("Pragma", "No-cache");
            response.setHeader("Content-Type", "text/html");
            response.setHeader("Cache-Control", "no-cache");
            response.setDateHeader("Expires", 0);
            response.getWriter().write(content);
            response.getWriter().flush();
        } catch (IOException e) {
            e.printStackTrace();
            logger.error("json转换错误", e);
        }
        return null;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值