jQuery+Ajax实现图片的预览和上传

jQuery+Ajax实现图片的预览和上传

1、配置Spring-web.xml
<!-- springmvc上传图片 -->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="defaultEncoding" value="utf-8"></property>
        <property name="maxUploadSize" value="10485760000"></property>
        <property name="maxInMemorySize" value="40960"></property>
    </bean>
2、引用jQuery的插件ajaxFileUpload.js

地址:
https://github.com/carlcarl/AjaxFileUpload
在线引用一直没有效,就直接下载放到js文件夹中。

3、jsp代码
<div >

    <label >点击图片即可修改</label><br>

    <img id="headPic" src="/market/images/image.png"  width="150px" height="150px" style="padding: 5px">
    <input id="upload" name="file" accept="image/*" type="file" style="display: none"/>

    <button id="submit_btn" type="submit">确定修改</button>
</div>
4、js代码
$(function() {
    //头像预览
    $("#headPic").click(function () {
        $("#upload").click(); //隐藏了input:file样式后,点击头像就可以本地上传
        $("#upload").on("change",function(){
            var objUrl = getObjectURL(this.files[0]) ; //获取图片的路径,该路径不是图片在本地的路径
            if (objUrl) {
                $("#headPic").attr("src", objUrl) ; //将图片路径存入src中,显示出图片
            }
        });
    });

     //图片上传
    $("#submit_btn").click(function () {

        var imgurl = document.getElementById("upload").value;

        $.ajaxFileUpload({
            url:"uploadHeadPic",
            fileElementId: "upload", //文件上传域的ID,这里是input的ID,而不是img的
            dataType: 'json', //返回值类型 一般设置为json
            contentType: "application/x-www-form-urlencoded; charset=utf-8",
            success: function (data) {
                alert(data.code+" "+ data.msg);
                if (data.code==200){

                    $("#headPic").attr("src","/market/images/image.png");
                    //将图片换成默认的+图片
                }
               =
            }

        });


    });

});

//建立一個可存取到該file的url
function getObjectURL(file) {
    var url = null ;
    if (window.createObjectURL!=undefined) { // basic
        url = window.createObjectURL(file) ;
    } else if (window.URL!=undefined) { // mozilla(firefox)
        url = window.URL.createObjectURL(file) ;
    } else if (window.webkitURL!=undefined) { // webkit or chrome
        url = window.webkitURL.createObjectURL(file) ;
    }
    return url ;
}
5、后台java代码
@RequestMapping(value = "/uploadHeadPic"
            , method = RequestMethod.POST
            , produces = "application/json; charset=utf-8")
    @ResponseBody
    public Object uploadHeadPic(@RequestParam() MultipartFile file, HttpServletRequest request) {
        //在这里面文件存储的方案一般是:收到文件→获取文件名→在本地存储目录建立防重名文件→写入文件→返回成功信息
        //如果上面的步骤中在结束前任意一步失败,那就直接失败了。
        FileOutputStream out=null;
        if (null == file || file.isEmpty()) {
            responseObj = new ResponseObj();
            responseObj.setCode(400);
            responseObj.setMsg("文件不能为空");

        }else{

            responseObj = new ResponseObj();
            responseObj.setCode(200);
            responseObj.setMsg("文件上传成功");

            //这里以用户ID作为文件夹
            int uid = (Integer) request.getSession().getAttribute("userid");
            //创建一个文件夹,网上代码很多
            String url = new FileUtil().createImageDir( String.valueOf(uid));
            try {
            //获得二进制流并输出
                byte[] f = file.getBytes();
                out = new FileOutputStream(url+file.getOriginalFilename());
                out.write(f);

            } catch (IOException e) {
                System.out.println("上传失败");
                responseObj.setCode(500);
                responseObj.setMsg("文件保存失败");
            }finally {
                // 完毕,关闭所有链接
                try {
                    out.close();
                } catch (IOException e) {
                    System.out.println("关闭流失败");
                }
            }

        }

        return new GsonUtil().CollectionToJson(responseObj);
    }
//在获得file后,打印下面信息
System.out.println(file.getContentType());
System.out.println(file.getOriginalFilename());
System.out.println(file.getName());

image/png      //input配置的 accept="image/*"
clipboard.png  //上传的图片名
file           //这个flie是input的name属性决定

现在有个问题是,在上传图片后,第二次点击上传,这时上传的图片依旧是之前的值,尝试多种清空input的file值也没有用。 
以下方法都不行

var file = doucment.getElementById('file');
//1
file.value = ''; //虽然file的value不能设为有字符的值,但是可以设置为空值
//2
file.outerHTML = file.outerHTML; //重新初始化了file的html
//3
var obj = document.getElementById('fileupload') ; 
obj.select(); 
document.selection.clear(); 

---------------------
作者:HYeeee 
来源:CSDN 
原文:https://blog.csdn.net/hyeeee/article/details/78594907?utm_source=copy 
版权声明:本文为博主原创文章,转载请附上博文链接!

猜你喜欢

转载自www.cnblogs.com/llhWeb/p/9766648.html
今日推荐