zoukankan      html  css  js  c++  java
  • 05、SpringBoot上传图片

    说明:通常项目中,如果图片比较多的话,都会把图片放在专门的服务器上,而不会直接把图片放在业务代码所在的服务器上。下面的例子只是为了学习基本流程,所以放在了本地。

    1、单张图片上传

    1.1、前端用表单提交

    前端代码:

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
    <form method="post" action="/uploads" enctype="multipart/form-data">
        <input type="file" name="files" multiple>
        <input type="submit" value="上传">
    </form>
    </body>
    </html>

    后端代码;

    SimpleDateFormat formatter = new SimpleDateFormat("/yyyy/MM/dd/");
        @RequestMapping("/upload")
        public String fileUpload(MultipartFile file, HttpServletRequest request){
            String time = formatter.format(new Date());
            //图片上传服务器后所在的文件夹
            String realPath = request.getServletContext().getRealPath("/img") + time;
            File folder = new File(realPath);
            if(!folder.exists())
                folder.mkdirs();
    
            //通常需要修改图片的名字(防止重复)
            String oldName = file.getOriginalFilename();
            String newName = UUID.randomUUID() + oldName.substring(oldName.lastIndexOf("."));
    
            try {
                //将文件放到目标文件夹
                file.transferTo(new File(folder, newName));
    
                //通常还需要返回图片的URL,为了通用性,需要动态获取协议,不要固定写死
                String returnUrl = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + "/img" + time + newName;
                return returnUrl;
            } catch (IOException e) {
                e.printStackTrace();
            }
    
    
            return null;
        }

    1.2、前端用ajax提交

    前端代码与上面的略有不同,后台代码是一样的。

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    
    </head>
    <body>
        <input type="file" id="file">
        <input type="submit" value="上传" onclick="uploadFile()">
    <h1 id="result"></h1>
    </body>
    
    <script src="https://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js">
    </script>
    <script>
    function uploadFile() {
        var file = $("#file")[0].files[0];
        var formData = new FormData();
        formData.append("file", file);
        $.ajax({
            type:"post",
            url:"/upload",
            processData:false,
            contentType:false,
            data:formData,
            success:function (msg) {
                $("#result").html(msg);
            }
        })
    }
    </script>
    </html>

    2、多个图片上传

    前端代码:

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
    <form method="post" action="/uploads" enctype="multipart/form-data">
        <input type="file" name="files" multiple>
        <input type="submit" value="上传">
    </form>
    </body>
    </html>

    后台代码:

        @RequestMapping("/uploads")
        public String fileUploads(MultipartFile[]files, HttpServletRequest request){
            String time = formatter.format(new Date());
            //图片上传服务器后所在的文件夹
            String realPath = request.getServletContext().getRealPath("/img") + time;
            File folder = new File(realPath);
            if(!folder.exists())
                folder.mkdirs();
    
            for (MultipartFile file : files) {
                //通常需要修改图片的名字(防止重复)
                String oldName = file.getOriginalFilename();
                String newName = UUID.randomUUID() + oldName.substring(oldName.lastIndexOf("."));
    
                try {
                    //将文件放到目标文件夹
                    file.transferTo(new File(folder, newName));
    
                    //通常还需要返回图片的URL,为了通用性,需要动态获取协议,不要固定写死
                    String returnUrl = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + "/img" + time + newName;
                    System.out.println(returnUrl);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
    
            return null;
        }

    3、问题记录

    在后台代码中,有一行需要注意下:

     String realPath = request.getServletContext().getRealPath("/img") + time;

    需要理解一下realPath究竟指的是什么。刚开始测试的时候,图片上传成功后,后台idea里找不到对应的图片,然后根据它返回的realPath,在C盘用户目录下的某个文件夹里找到了该图片(user/AppData/....)。

    参考博客: https://www.cnblogs.com/netcorner/p/12001668.html

    shift+shift 全局搜索  getCommonDocumentRoot这个方法,点进去,有个静态数组:COMMON_DOC_ROOTS

        private static final String[] COMMON_DOC_ROOTS = new String[]{"src/main/webapp", "public", "static"};

    发现默认是指webapp下,或者根目录下的public、static文件夹(与src并列)。然而这些目录都没有,所以Spring定向到了工程目录以外的一个位置。

    于是我在根目录下新建一个static文件夹,再次上传,果然有效了。

     
  • 相关阅读:
    codevs1227 方格取数2 注意数组啊啊啊啊啊啊啊啊啊啊
    codevs1033 蚯蚓的游戏问题 裸最小费用最大流,注意要拆点
    模板题 codevs 1993 草地排水 想学习的请看链接
    java初级易错问题总结
    JAVA基本数据类型所占字节数是多少?
    forword和重定向有什么区别?
    Spring框架注解
    hibernate利用mysql的自增张id属性实现自增长id和手动赋值id并存
    eclispe中安装hibernate插件
    struts2使用模型传值
  • 原文地址:https://www.cnblogs.com/phdeblog/p/13236363.html
Copyright © 2011-2022 走看看