欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

表单上传图片并显示

程序员文章站 2022-07-15 11:45:02
...
package com.lanou;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.Date;

@Controller
public class TestController {

    @ResponseBody

    @PostMapping("/upload2")
    public String aa(MultipartFile img, HttpServletRequest request) throws IOException {
        System.out.println(img.getSize());
        //获取文件保存地址目录
        String realPath = request.getServletContext().getRealPath("/imgs");
        //生成一个文件名
        String imgName=new Date().getTime()+".jpg";
        //保存文件(复制)
//        IOUtils.
        FileUtils.copyToFile(img.getInputStream(),new File(realPath+"/"+imgName));
        //获取文件的访问地址
        String imgUrl="/imgs/"+imgName;
        System.out.println(imgUrl);
        return imgUrl;
    }
}

<html>
<head>
    <script src="/lib/jquery-3.2.1.min(1).js"></script>
    <script src="/lib/jquery.form.js"></script>
</head>
<body>
<h2>Hello World!</h2>
<form id="uploadForm" >
    <input type="file" name="img">
    <button type="button" id="uploadBtn">upload</button>




<script>
    $("#uploadBtn").click(function () {
        //提交当前表单
        $("#uploadForm").ajaxSubmit({
            url:"/upload2",
            type:"post",
            success:function (data) {
                alert(data);

                var img='<img src="'+data+'"/>';
                $("#uploadForm").after(img);
            }
        })
    });


</script>
</form>
</body>
</html>

或者

<html>
<head>
    <script src="/lib/jquery-3.2.1.min(1).js"></script>
    <script src="/lib/jquery.form.js"></script>

    <style>
        #img_img:hover {
            cursor: pointer;
            border: #333333 solid 1px;
        }
    </style>
</head>
<body>
<h2>Hello World!</h2>
<form id="uploadForm">
    <%--图片上传按钮隐藏--%>
    <input type="file" name="img" style="display: none">
    <img src="1.jpg" id="img_img" style="width: 100px; height: 100px;">

</form>


<script>

    $("#img_img").click(function () {
        //点击图片**上传按钮
        $("input[name='img']").click();
    });

    $('input[name="img"]').change(function () {
        //提交当前表单
        $("#uploadForm").ajaxSubmit({
            url: "/upload2",
            type: "post",
            success: function (data) {
                // alert(data);

                var img = '<img src="' + data + '"/>';
                $("#img_img").attr("src", data);
            }
        })
    });


</script>
</form>
</body>
</html>

相关标签: 前后端结合