2023-04-25 10:38

SpringMVC+ajax 多图片上传并回显

wanmatea

JavaEE

(410)

(0)

收藏

页面代码:

<div id="pimg">
    <input type="hidden" id="pic" name="pic" value="${p.pic}">
</div>
<input class="common-text required" id="file" name="file" size="50" value="" type="file" multiple>

js代码:

$("#pimg div p").click(function (){
    $(this).parent().remove();
    var pic=$("#pic").val();
    var p=$(this).data("pic");
    //abc indexOf("a")
    //index(子字符串) 返回子字符串在字符串中的索引 如果没有返回-1
    if(pic.indexOf(p+",")>=0){
        pic=pic.replace(p+",","");
    }
    else if(pic.indexOf(","+p)>=0){
        pic=pic.replace(","+p,"");
    }
    else if(pic.indexOf(p)>=0){
        pic=pic.replace(p,"");
    }
    $("#pic").val(pic);
});
$("#file").change(function (){
    var length=$("#file")[0].files.length;
    if(length>5){
        alert("最多上传5个图片");
        return;
    }
    //html对象 jquery对象->html对象 jquery对象[0]  html对象->jquery对象 $(html对象)
    var formData=new FormData($("#myform")[0]);
    $.ajax({
        url:"${path}/manage/product/upload",
        type:"post",
        data:formData,
        contentType:false,
        processData:false,
        success:function (data){
            var arr=data.split(",");
            for(var p of arr){
                var img=$("<img>");
                img.attr("src","${path}"+p);
                $("#pimg").append(img);
            }
            var pic=$("#pic").val();
            if(pic!=""){
                $("#pic").val(pic+","+data);
            }
            else{
                $("#pic").val(data);
            }
        }
    });
});

控制器上传方法代码:

@PostMapping("add")
public String add(MultipartFile file, Product product, HttpServletRequest request) throws IOException {
    //获得提交图片的名字
    String fileName=file.getOriginalFilename();
    //获得图片的后缀名
    String fileExt=fileName.substring(fileName.lastIndexOf("."));
    //生成一个唯一的名字
    String newFileName= UUID.randomUUID().toString().replace("-","")+fileExt;
    //获得当前运行项目的真实路径
    String path=request.getServletContext().getRealPath("/")+"images/"+newFileName;
    //保存图片
    file.transferTo(new File(path));
    product.setPic("/images/"+newFileName);
    ProductDAO.getDAO().add(product);
    return "redirect:/manage/product/list";
}


实现效果:

image.png

0条评论

点击登录参与评论