当前位置 博文首页 > 谢哥哥的博客:【文件上传】Java文件本地上传,并以http方式浏览

    谢哥哥的博客:【文件上传】Java文件本地上传,并以http方式浏览

    作者:[db:作者] 时间:2021-07-13 13:13

    在平常的开发中,难免遇到上传图片的问题,又没有测试服务器的时候,你和前端对接接口,发现图片上传之后回显不出来,是一个磁盘路径:(如下图)像这种情况可以通过tomact下的功能实现,代码实现很简单,并且返回的也是http路径。

    在这里插入图片描述

    解决:图片不回显问题

    注册了ServletContext后,springboot项目启动的时候会在c盘:
    C:\Users\MAIBENBEN\AppData\Local\Temp下生成类似(如下)的文件夹
    在这里插入图片描述
    生成的图片就在这个文件夹下

    在代码中也把路径打印了出来
    在这里插入图片描述
    照这这个路径找就能找到图片的存储路径

    下面代码实现

    实现:文件上传本地,以http的方式回显前端

    UploadFileController

    package xgg.springboot.base.controller;
    
    import io.swagger.annotations.ApiOperation;
    import lombok.RequiredArgsConstructor;
    import lombok.extern.slf4j.Slf4j;
    import org.apache.commons.io.FileUtils;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.web.bind.annotation.PostMapping;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RestController;
    import org.springframework.web.multipart.MultipartFile;
    import xgg.springboot.common.util.GetIpAddressUtil;
    
    import javax.servlet.ServletContext;
    import java.io.File;
    import java.io.IOException;
    import java.io.InputStream;
    import java.util.HashMap;
    import java.util.Map;
    import java.util.UUID;
    
    /**
     * @author xiegege
     * @date 2020/12/7 14:03
     */
    @Slf4j
    @RestController
    @RequestMapping("upload")
    @RequiredArgsConstructor(onConstructor = @__(@Autowired))
    public class UploadFileController {
    
        private final ServletContext context;
    
        @PostMapping("upload-image")
        public Map<String, String> upload(MultipartFile file) throws IOException {
            //参数校验
            if (file == null) {
                throw new IllegalArgumentException("file or filename object is null");
            }
            // 获取文件类型
            String contentType = file.getContentType();
            // 获取文件后缀
            String ext = contentType.substring(contentType.lastIndexOf("/") + 1);
            // uuid生成文件名 + 后缀
            String fileName = UUID.randomUUID() + "." + ext;
            // 返回url路径
            String url = "http://" + GetIpAddressUtil.getIpAddress() + ":8000/statics/attachment/" + fileName;
            // 本地磁盘存储路径
            String filePath = context.getRealPath("/") + "statics/attachment/" + fileName;
            log.info("入库本地磁盘路径:" + filePath);
            // 写入文件
            write(file.getInputStream(), filePath);
            // 返回数据
            Map<String, String> dataMap = new HashMap<>(3);
            dataMap.put("name", fileName);
            dataMap.put("url", url);
            dataMap.put("ext", ext);
            return dataMap;
        }
    
        /**
         * 将inputStream写入文件
         *
         * @param stream 文件流
         * @param path   要写入的文件路径
         */
        private static void write(InputStream stream, String path) {
            try {
                FileUtils.copyInputStreamToFile(stream, new File(path));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    

    GetIpAddressUtil

    public class GetIpAddressUtil {
    
        public static void main(String[] args) {
            System.out.println("本机IP:" + getIpAddress());
        }
    
        public static String getIpAddress() {
            try {
                Enumeration<NetworkInterface> allNetInterfaces = NetworkInterface.getNetworkInterfaces();
                InetAddress ip;
                while (allNetInterfaces.hasMoreElements()) {
                    NetworkInterface netInterface = allNetInterfaces.nextElement();
                    if (netInterface.isLoopback() || netInterface.isVirtual() || !netInterface.isUp()) {
                        continue;
                    } else {
                        Enumeration<InetAddress> addresses = netInterface.getInetAddresses();
                        while (addresses.hasMoreElements()) {
                            ip = addresses.nextElement();
                            if (ip instanceof Inet4Address) {
                                return ip.getHostAddress();
                            }
                        }
                    }
                }
            } catch (Exception e) {
                System.err.println("IP地址获取失败" + e.toString());
            }
            return "";
        }
    }
    
    

    调用接口

    在这里插入图片描述

    访问路径

    在这里插入图片描述
    图片正常显示 这里的192.168.52.1是我的本机ip
    图片
    前端回显也正常了。搞定,现在可以摸鱼 摸起来了。

    需要注意的地方

    项目启动后每次都会生成新的文件夹
    在这里插入图片描述
    之前传入的文件就访问不到了,所以在测试一套流程的时候,尽量后端避免重启服务,或者是把之前的图片全部剪切到新生成的文件中。

    总结

    如果觉得不错,可以点赞+收藏或者关注下博主。感谢阅读!

    cs