图片的上传 spring mvc

图片的上传依赖于jquery-1.8.3.js  jquery.form.js两个js包,前端通过file选择图片时,会触发js方法,该方法将数据转换为json数据,传入后端。此时后端接收图片后并进行相关操作,将在服务器的webapp下创建upload(名称是随意的)文件夹存储图片,将把图片路径返回给前端,前端的js接收到图片路径后,给img标签赋值。img显示图片。

前端通过js上传图片--》后端接收传递过来的图片 处理并存储--》后端将图片url返回前端--》前端通过js给img的src属性赋值

图片的上传分为三步(Thymeleaf+Spring boot):

1、将jquery-1.8.3.js  jquery.form.js  两个包放入项目中,并在网页中引用如Thymeleaf是把js放入 resources->static->Js 文件中,引用格式为 

<script src="../Js/jquery-1.8.3.js"></script>
<script src="../Js/jquery.form.js"></script>
jsp是放入 webapp->js 中 引用为
<script src="${pageContext.request.contextPath}/js/jquery-1.8.3.js"></script>
<script src="${pageContext.request.contextPath}/js/jquery.form.js"></script>

2、编写html

<html>
<head>
    <title>Title</title>
    <script src="../Js/jquery-1.8.3.js"></script>
    <script src="../Js/jquery.form.js"></script>
    <script>
        function submitImage() {
            alert("提交图片到后台");

            //封装请求数据
            var options = {
                type:'post',
                data:{
                    username:'  '
                },
                dataType:'json',
                url:'/itemspic',
                //itemspic是后端控制器@RequestMapping("/itemspic")                
                success:function (respData) { //此方法,接收后端传递回来的数据,并给id为pic与hiddenPic的标签赋值
                    console.log(respData.imgUrl);
                    $('#pic').attr('src',respData.imgUrl);
                    $('#hiddenPic').val(respData.imgUrl)
                }
            }

            //提交表单 itemsForm是表单的id
            $('#itemsForm').ajaxSubmit(options) 
         
        }
    </script>
</head>
<body>
<form id="itemsForm" action="#" method="post">
    <table border="1">
        <tr>
            <td>图片</td>
            <td>
                <img id="pic" src="#" width="100px" height="100px">
                <input type="file" name="itemspic1" onChange="submitImage();">
                <input id="hiddenPic" name="imgurl" type="hidden" value="#">

        </tr>
    </table>
</form>
</body>
</html>

3,编写后端

 @RequestMapping("/itemspic")
    public void itemspic(HttpServletRequest request, HttpServletResponse response) throws Exception {
        MultipartHttpServletRequest mutliRequest = (MultipartHttpServletRequest) request;
        //1.获取图片数据
        MultipartFile mfile = mutliRequest.getFile("itemspic1");
        //2.把图片保存在某个路径
        //2.1文件保存的文件夹路径,不存在则创建一个
        String uploadFolder = request.getServletContext().getRealPath("/upload");
        File uploadFolderFile = new File(uploadFolder);
        if(!uploadFolderFile.exists()){
            //为什么用mkdirs()呢?因为这个方法可以在不知道偶没有父类文件夹的情况下,创建文件夹,而mkdir()必须在有父类的文件夹下创建文件
            uploadFolderFile.mkdirs(); 
        }

        //2.2.文件
//        file.getOriginalFilename()是得到上传时的文件名。  split是java分隔函数
        String suffix = mfile.getOriginalFilename().split("\\.")[1];

//        replaceAll("-", "")意思就是把其中的-换成空字符串,,也就是把-去掉
//        文件名是uuid自动生成的。 后缀是通过suffix得到的
        String fileName = UUID.randomUUID().toString().replace("-","") + "." + suffix;
        //得到完整的路径
        String totalPath = uploadFolder + "\\" + fileName;
//        System.out.println("totalpath:" + totalPath);
        //把图片数据写入文件
        FileCopyUtils.copy(mfile.getInputStream(),new FileOutputStream(new File(totalPath)));
        //返回数据给客户端 127.0.0.1:8080 如果是服务器应用换成真实的ip地址
        String imgURL = "http://127.0.0.1:8080/upload/" + fileName;
        String responseJson = "{\"imgUrl\":\"" + imgURL  + "\"}";
        response.setHeader("content-type","text/json;charset=utf-8");
        response.getWriter().write(responseJson); //把图片的url返回给前端
    }

注意: jquery-1.8.3.js  jquery.form.js  容易和别的js包冲突。如jquery.js。当发生时应当删除与这冲突的。

由于水平有限,代码有误请连接 QQ:2742887166

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值