Ajax简单异步上传图片并回显

Posted yxmhl

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Ajax简单异步上传图片并回显相关的知识,希望对你有一定的参考价值。

前台代码

上传图片按钮

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

隐藏的文件选择器

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

图片预览

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

去除图片预览未选择时默认时的边框

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

JavaScript部分

<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>

后台代码

    /**
     * 图片上传
     * @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;
    

以上是关于Ajax简单异步上传图片并回显的主要内容,如果未能解决你的问题,请参考以下文章

图片上传并回显后端篇

Spring Boot 实现多图片上传并回显,涨姿势了~

uview+uniapp+springboot 实现小程序上传图片并回显

上传图片至fastdfs分布式文件系统并回显

Spring Boot 实现多图片上传并回显,涨姿势了~

如何用input标签上传多个图片并回显