Ajax asynchronous upload pictures and simple echo

Reception Code

Upload Picture button

<a href="javascript:void(0)" onclick="uploadPhoto()">选择图片</a>

Hidden file selector

<input type="file" id="photoFile" style="display: none;" onchange="upload()">

Picture Preview

<img id="preview_photo" src="" width="200px" height="200px">

When the removal of borders is not selected by default when image preview

<style>
    img[src=""],img:not([src]){
        opacity:0;
    }
</style>

JavaScript section

<script>
    function uploadPhoto() {
        $("#photoFile").click();
    }

    /**
     * 上传图片
     */
    function upload() {
        if ($("#photoFile").val() == '') {
            return;
        }
        var formData = new FormData();
        formData.append('photo', document.getElementById('photoFile').files[0]);
        $.ajax({
            url:"${pageContext.request.contextPath}/system/uploadPhoto",
            type:"post",
            data: formData,
            contentType: false,
            processData: false,
            success: function(data) {
                if (data.type == "success") {
                    $("#preview_photo").attr("src", data.filepath+data.filename);
                    $("#productImg").val(data.filename);
                } else {
                    alert(data.msg);
                }
            },
            error:function(data) {
                alert("上传失败")
            }
        });
    }
</script>

Background code

    /**
     * 图片上传
     * @param photo
     * @param request
     * @return
     */
    @RequestMapping(value = "/uploadPhoto", 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() > 1024 * 1024 * 10) {
            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;
        }
        //获取项目根目录加上图片目录 webapp/static/imgages/upload/
        String savePath = request.getSession().getServletContext().getRealPath("/") + "/static/images/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) {
            ret.put("type", "error");
            ret.put("msg", "保存文件异常!");
            e.printStackTrace();
            return ret;
        }
        ret.put("type", "success");
        ret.put("msg", "上传图片成功!");
        ret.put("filepath", request.getSession().getServletContext().getContextPath() + "/static/images/upload/");
        ret.put("filename", filename);
        return ret;
    }

Guess you like

Origin www.cnblogs.com/yxmhl/p/11617497.html