0

    Springboot上传图片和回显示图片

    2023.06.21 | admin | 134次围观

    本次演示的是直接使用Springboot上传到服务器而不是七牛云等ossvb上传图片到服务器,springboot对于前端传输的文件数据类型格式的封装为MultipartFile,前端上传的图片是被存在服务端的缓存区的,当controller处理的时候,缓存区就被清空,所以需要转存,使用transferTo Api

    前端采用elementui 直接上传图片

    游览器查看内容

    vb上传图片到服务器_jsp上传图片到指定空间_vb上传图片到服务器

    发送的内容image/jpeg等格式

    后端:

    先对源文件名的后缀做一个截取,保证格式不变,然后对文件名采用uuid加时间搓保证唯一性vb上传图片到服务器,在使用对响应体写数据的方式完成回显

       @Value("${photo.path}")
        String path;
        @PostMapping("upload")
        public R<String> upload(MultipartFile file){
            if (Objects.isNull(file)){
                return  R.error("上传错误");
            }
    //        1.判断当前目录是否存在
            File dir = new File(path);
            if(!dir.exists()){
    //            不纯在的话就根据路径来创建对应文件夹
                dir.mkdirs();
            }
            log.info("通用接口接受到图片:{}",file);
            /**
             * 上传完的文件 是暂时缓存到 tomcat服务器上的  ,转存到另一个位置
             */
            try {
    //            获取后缀
                String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf('.'));
                    String fileName=UUID.randomUUID().toString() + new Date().getTime() +suffix;
    //            实际是保存到图片服务器
                file.transferTo(new File(path + fileName));
                return R.success(fileName);
            } catch (IOException e) {
                throw new CustomerException("创建失败");
            }
        }
    @GetMapping("download")
        public void download(@RequestParam String name , HttpServletResponse response){
    //        设置相应体输出的类型
            response.setContentType("image/jpeg");
    //        对游览器的相应体进行下载
    //        1.input输入流 读取文件
            try {
                FileInputStream fileInputStream = new FileInputStream(new File(path+name));
                OutputStream outputStream = response.getOutputStream();
                byte[] bytes = new byte[1024];
                int len=0;
    //           2. 对文件进行读取  并且赋值给长度
                while ((len=fileInputStream.read(bytes))!=-1){
    //              3.流写入相应体
        outputStream.write(bytes, 0, len);
        outputStream.flush();
                }
                fileInputStream.close();
                outputStream.close();
                     } catch (Exception e) {
                throw new CustomerException("Common::log::DOWNLOAD" +
                        "::图片获取失败:"+e.getMessage());
            }
    //        2.output输出流进行展示图片
        }
    

    版权声明

    本文仅代表作者观点。
    本文系作者授权发表,未经许可,不得转载。

    发表评论