JAVA上传图片文件到服务器

HTML部分:

现在有一个表格,表格的第一个td中是一个图片上传的input框

<td id="iconTd" rowspan="4" style="background-image: url('<%=basePath%>/static/images/niu.jpg');
        background-size: 100% 100%">
    <input type="file" id="file" name="imgFile" accept="image/jpeg,image/jpg,image/png" onchange="showIncon(this)">
</td>

td的背景图片放置一张默认图片,这里我放了一张牛的图片

input框中添加属性accept="image/jpeg,image/jpg,image/png"来限制只能上传这三种格式的图片文件,想要添加更多类型可以自行百度相关的MIME格式添加进去

input框添加了onchange方法,图片更换时被调用

CSS部分:

这里我为input框添加了样式{opacity:0;width:100%;height:100%},既实现了input上传文件按钮的隐藏,又可以点击整个td区域都能弹出上传窗口

JS部分

showIncon(file)方法:

 
function showIncon(file){
    var r= new FileReader();
    //由于jQuery对象没有 files 属性,此处要使用原生js获取,或者$("#file")[0].files;
    f = document.getElementById('file').files[0];
    //限制上传图片大小在2M以内,超过2M则显示默认图片,并清空input框的值
    if(f.size>2048000){
        alert( "请上传小于2M的图片");
        $("#iconTd").css("background-image","url('<%=basePath%>/static/images/niu.jpg')");
        file.value = "";
    }else{
        r.readAsDataURL(f);
        r.onload=function  (e) {
            $("#iconTd").css("background-image","url(" + this.result + ")");
        };
    }
}

上传到服务器上:

table是放在一个form中的,form的属性如下:

<form id="stuForm" method="post" enctype="multipart/form-data" action="<%=basePath%>/student/addStudent">

表单提交后进入后台,Controller部分:

@RequestMapping(value="student/addStudent",method = RequestMethod.POST)
@ResponseBody
public String addStudent(HttpServletRequest req, Model model) throws IOException {
    //图片上传到服务器
    CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver(
            req.getSession().getServletContext());
    commonsMultipartResolver.setDefaultEncoding("utf-8");
    MultipartHttpServletRequest multipartRequest = commonsMultipartResolver
            .resolveMultipart(req);
    MultipartFile multipartFile = multipartRequest.getFile("imgFile");
    //获取绝对路径 并在指定相应目录创建File对象
    String contextPath = req.getSession().getServletContext().getRealPath("/");
    String fileName = "xxx.jpg";
    File imgFile = new File(contextPath+"/static/images/"+fileName);
    //上传文件
    multipartFile.transferTo(imgFile);

    return "要跳转的路径";
}

猜你喜欢

转载自blog.csdn.net/weixin_39463716/article/details/80672658