localResizeIMG先压缩后ajax无刷新上传图片

时间:2021-09-30 19:59:58

css部分对按钮美化

<input type="file" name="file" class="upload" accept="image/jpeg,image/jpg,image/png">
<a href="javaScript:void(0);"  class="but" onclick="$(this).siblings('.upload').click();">上传</a>

javascript部分
引入js,可自行下载
 
<script src="/static/jquery/jquery-1.8.3.min.js" type="text/javascript"></script>
 
<script src="/static/uploader/LocalResizeIMG.js" type="text/javascript"></script>
<script src="/static/uploader/mobileBUGFix.mini.js" type="text/javascript"></script>

 
$(".upload").on("click", function () {
    var sibForm = $(this);
    var form = $(this).siblings("a");
    $(this).localResizeIMG({
        width: 800, //上传图片后的大小
        quality: 1,  
        before: function (that, blob) {
            form.html("正在上传");
        },
        success: function (result) {

            var submitData = {
                base64_string: result.clearBase64,
            };
            $.ajax({
                type: "POST",
                url: "/insurance/upload",
                data: submitData,
                dataType: "json",
                success: function (data) {
                    if (0 == data.status) {
                        alert(data.content);
                        return false;
                    } else {   //图片同步到页面,根据自己需要,url为图片地址
var html = '<input type="hidden" value="' + data.url + '" name="' + form.data("state") + '"></input>';
                        $("#submitForm").append(html);var attstr = '<a href="'+data.url+'" target="_blank" id="' + form.data("state") + '" ><img src="' + data.url + '"></a>';
                        $(".uploadImgItem a").each(function (index, value) {
                            if ($(this).attr("id") == form.data("state")) {
                                $("#" + form.data("state")).remove();
                            }
                        });
                        $(".uploadImgItem").append(attstr);

                    }
                },
                complete: function (XMLHttpRequest, textStatus) {
                    form.html("上传成功")
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) { //上传失败  //alert(XMLHttpRequest.status);  //alert(XMLHttpRequest.readyState);  //alert(textStatus);  form.html("上传失败");
                }
            });
        }
    });
})

java部分

@RequestMapping(value = "upload")
public String uploadHeadPic(HttpServletRequest request,HttpServletResponse response) throws IOException {
    try {
        String fileBase64 = request.getParameter("base64_string");
        if(fileBase64.startsWith("data:image/jpeg;base64,")){
            fileBase64 = fileBase64.replaceFirst("data:image/jpeg;base64,", "");
        }
        Calendar c = Calendar.getInstance();
        String destDir = "/upload/images/"+c.get(Calendar.YEAR)+"/" + (c.get(Calendar.MONTH)+1)+"/"+c.get(Calendar.DATE)+"/";
        String fileName= uploadBase64(destDir,fileBase64,request);
        response.getWriter().write("{\"status\":1,\"content\":\"上传成功\",\"url\":\""+fileName+"\"}");
    } catch (Exception e) {
        e.printStackTrace();
        response.getWriter().write("{'status':0,'content':'上传失败'}");
    }
    return null;
}

public String uploadBase64(String destDir,String base64str,HttpServletRequest request){

    byte[] fileData = Base64.base64ToByteArray(base64str);
    String realPath = request.getSession().getServletContext().getRealPath("/");
    File destFile = new File(realPath+destDir);
    if(!destFile.exists()){
        destFile.mkdirs();
    }
    String fileNameNew =getFileNameNew()+".jpg";
    FileUtils.wirteToFile(destFile.getAbsoluteFile()+"/"+fileNameNew, fileData);
    System.out.println(destFile.getAbsoluteFile()+"/"+fileNameNew);
    return destDir+fileNameNew;
}