feign文件上传

news2024/10/7 10:31:05

记录一下

feign文件上传

  • 环境
    • spring-boot 2.3.7
     <parent>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-starter-parent</artifactId>
          <version>2.3.7.RELEASE</version>
          <relativePath/> <!-- lookup parent from repository -->
      </parent>
    
    • 依赖引入
     <dependency>
             <groupId>org.springframework.cloud</groupId>
             <artifactId>spring-cloud-starter-openfeign</artifactId>
             <version>2.1.0.RELEASE</version>
         </dependency>
    
    • 网上版本的依赖
    <!-- Feign文件上传依赖-->
    <dependencies>
    <dependency>
     <groupId>io.github.openfeign.form</groupId>
     <artifactId>feign-form</artifactId>
     <version>3.8.0</version>
    </dependency>
    <dependency>
     <groupId>io.github.openfeign.form</groupId>
     <artifactId>feign-form-spring</artifactId>
     <version>3.8.0</version>
    </dependency>
    </dependencies>dependency>
    

    和你的feign依赖有关,自己判断下,2.1.0已经包含了在这里插入图片描述

配置文件

import feign.codec.Encoder;
import feign.form.spring.SpringFormEncoder;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.cloud.openfeign.support.SpringEncoder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.context.annotation.Scope;

@Configuration
public class FeignMultipartSupportConfig {
    @Autowired
    private ObjectFactory<HttpMessageConverters> messageConverters;
    @Bean
    @Primary
    @Scope("prototype")
    public Encoder multipartFormEncoder() {
        return new SpringFormEncoder(new SpringEncoder(messageConverters));
    }

    @Bean
    public feign.Logger.Level multipartLoggerLevel() {
        return feign.Logger.Level.FULL;

    }

}

feign接口

import com.alibaba.fastjson.JSONObject;
import com.zzg.web.config.FeignMultipartSupportConfig;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.multipart.MultipartFile;

/**
 * @program: atomic-upms
 * @description:
 * @author: zzg@xnj
 * @create: 2024-08-20 16:50
 **/
@FeignClient(value = "file-service", url = "${file-service}", configuration  = {FeignMultipartSupportConfig.class})
public interface FileFeign {


    @RequestMapping(value ="/file/fileUpload",method = RequestMethod.POST, consumes = {MediaType.MULTIPART_FORM_DATA_VALUE})
    JSONObject fileupload(@RequestPart(value="uploadfile") MultipartFile uploadfile) ;
}

service

@Service
public class FileService {

    @Resource
    private FileFeign fileFeign;

    public void uploadFile(MultipartFile file) {
        fileFeign.fileupload(file);
    }
}

controller

注意两个接口的区别

@Api(tags = "文件")
@RestController
@RequestMapping("/file")
public class UploadController {
    @Resource
    private FileService fileService;



    @ApiOperation("上传文件")
    @PostMapping("/fileUpload")
    public ResponseModel uploadFile(@RequestPart MultipartFile uploadfile) {


        fileService.uploadFile(uploadfile);

        return new ResponseModel("200","ok");
    }

    @ApiOperation("上传文件2")
    @PostMapping("/fileUpload2")
    public ResponseModel uploadFile2(@RequestPart MultipartFile file) {


        fileService.uploadFile(file);

        return new ResponseModel("200","ok");
    }
}
  • feign的对应的controller
 @ApiOperation("上传文件")
    @PostMapping("/fileUpload")
    public ResponseModel uploadFile(@RequestPart MultipartFile uploadfile) {


        fileService.uploadFile(uploadfile);

        return new ResponseModel("200","ok");
    }

运行结果

  • 调用fileUpload 接口 --》上传成功
  • 调用fileUpload2 接口 --》上传失败

远程端报错信息
在这里插入图片描述

解决

  • 问题原因 :前后端参数名对应不一致

可能原因:
前后端参数名对应不一致
spring.servlet.multipart.enabled=false即关闭文件上传支持
配置文件中指定了文件上传时的大小值问题
切换内嵌容器tomcat到undertow的配置问题
spring.servlet.multipart.location=/tmp指定了临时文件站,但路径不存在
多次读取HttpServletRequest流
springboot已经有CommonsMultipartResolver,需要排除原有的Multipart配置@EnableAutoConfiguration(exclude = {MultipartAutoConfiguration.class})
摘抄文章链接

  • 解决方案: 添加变量名,利用MultipartFile.getName
   @ApiOperation("上传文件2")
    @PostMapping("/fileUpload2")
    public ResponseModel uploadFile2(@RequestPart MultipartFile file) {


        try {
            file = new MultipartFileDto("uploadfile",file.getOriginalFilename(),file.getContentType(), file.getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        }

        fileService.uploadFile(file);

        return new ResponseModel("200","ok");
    }
 

import org.springframework.util.FileCopyUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;

/**
 * @program: atomic-upms
 * @description:
 * @author: zzg@xnj
 * @create: 2024-08-20 20:24
 **/

public class MultipartFileDto implements MultipartFile {
    private final String name;

    private String originalFilename;

    private String contentType;

    private final byte[] content;

    /**
     * Create a new MultipartFileDto with the given content.
     * @param name the name of the file
     * @param content the content of the file
     */
    public MultipartFileDto(String name, byte[] content) {
        this(name, "", null, content);
    }

    /**
     * Create a new MultipartFileDto with the given content.
     * @param name the name of the file
     * @param contentStream the content of the file as stream
     * @throws IOException if reading from the stream failed
     */
    public MultipartFileDto(String name, InputStream contentStream) throws IOException {
        this(name, "", null, FileCopyUtils.copyToByteArray(contentStream));
    }

    /**
     * Create a new MultipartFileDto with the given content.
     * @param name the name of the file
     * @param originalFilename the original filename (as on the client's machine)
     * @param contentType the content type (if known)
     * @param content the content of the file
     */
    public MultipartFileDto(String name, String originalFilename, String contentType, byte[] content) {
        this.name = name;
        this.originalFilename = (originalFilename != null ? originalFilename : "");
        this.contentType = contentType;
        this.content = (content != null ? content : new byte[0]);
    }

    /**
     * Create a new MultipartFileDto with the given content.
     * @param name the name of the file
     * @param originalFilename the original filename (as on the client's machine)
     * @param contentType the content type (if known)
     * @param contentStream the content of the file as stream
     * @throws IOException if reading from the stream failed
     */
    public MultipartFileDto(String name, String originalFilename, String contentType, InputStream contentStream)
            throws IOException {

        this(name, originalFilename, contentType, FileCopyUtils.copyToByteArray(contentStream));
    }

    @Override
    public String getName() {
        return this.name;
    }

    @Override
    public String getOriginalFilename() {
        return this.originalFilename;
    }

    @Override
    public String getContentType() {
        return this.contentType;
    }

    @Override
    public boolean isEmpty() {
        return (this.content.length == 0);
    }

    @Override
    public long getSize() {
        return this.content.length;
    }

    @Override
    public byte[] getBytes() throws IOException {
        return this.content;
    }

    @Override
    public InputStream getInputStream() throws IOException {
        return new ByteArrayInputStream(this.content);
    }

    @Override
    public void transferTo(File dest) throws IOException, IllegalStateException {
        FileCopyUtils.copy(this.content, dest);
    }

}

事后诸葛亮

  • feign调用

参数没有生效??在这里插入图片描述

在这里插入图片描述

  • 正常表单请求
    在这里插入图片描述
    在这里插入图片描述

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2193973.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

NIO实现聊天室之:一切都要从网络编程的基础开始聊起!

一、写在开头 大家好,Build哥回来啦!停更了大概2个月之久,之前有段时间去写小说去了,后来又因为公司活太多,牛马干的太投入,就拉下了博客的更新,国庆节期间,难得的闲下来,准备回归老本行啦。 大致的翻看了一下之前更新的内容,已经写到了Java的IO部分,作为网络传输…

通过 LLMs 自动探索量化投资策略

作者&#xff1a;老余捞鱼 原创不易&#xff0c;转载请标明出处及原作者。 写在前面的话&#xff1a; 本文提出了一个利用大型语言模型&#xff08;LLMs&#xff09;和多代理架构的新框架&#xff0c;用于量化股票投资和投资组合管理。该框架通过整合LLMs生成多样化的al…

SpringBoot项目:前后端打包与部署(使用 Maven)

文章目录 IDEA后端打包与部署&#xff08;使用 Maven&#xff09;1. 确保 Maven 已安装&#xff0c;并引入 pom 插件2. 清理并安装项目3. 定位生成的 JAR 包和配置文件4. 创建部署文件夹5. 上传到服务器 前端打包与部署&#xff08;使用 npm&#xff09;1. 确保 Node.js 和 npm…

提升LLM结果:何时使用知识图谱RAG

通过知识图谱增强 RAG 可以帮助检索&#xff0c;使系统能够更深入地挖掘数据集以提供详细的响应。 译自Boost LLM Results: When to Use Knowledge Graph RAG&#xff0c;作者 Brian Godsey。 有时&#xff0c;检索增强生成 (RAG) 系统无法深入文档集以找到所需的答案。我们可能…

同质化的卷需要支撑多样化的环境来调和

(*^__^*) 代价高昂的免费机器人课程{人工智能与机器人教育之个人感悟}_从事机器人工程专业或机器人方向相关课程开发3年多的时间,从编写控制机器人的第一-CSDN博客 如上这篇写于2016&#xff0c;发表在博客的时间是2018。 总是觉得要补充些什么&#xff0c;但是&#xff0c;…

【模板进阶】std::true_type和std::false_type

一、 s t d : : t r u e _ t y p e std::true\_type std::true_type和 s t d : : f a l s e _ t y p e std::false\_type std::false_type的实现 s t d : : t r u e _ t y p e std::true\_type std::true_type和 s t d : : f a l s e _ t y p e std::false\_type std::false_t…

Unity WebGL使用nginx作反向代理处理跨域,一些跨域的错误处理(添加了反向代理的配置依旧不能跨域)

反向代理与跨域描述 什么是跨域&#xff1f; 跨域&#xff08;Cross-Origin Resource Sharing, CORS&#xff09;是指在浏览器中&#xff0c;当一个网页的脚本试图从一个域名&#xff08;协议、域名、端口&#xff09;请求另一个域名的资源时&#xff0c;浏览器会阻止这种请求…

php常用的注释符号

如果没有安装vscode和小皮&#xff0c;请点击下方链接安装&#xff1a; Vscode、小皮面板安装-CSDN博客 在学习php过程中&#xff0c;肯定少不了注释&#xff0c;也可以理解为备注的信息&#xff0c;来提醒自己这段代码有什么用&#xff0c;是什么意思等&#xff0c;接下来就介…

JS测试框架——Jest

文章目录 安装yarn安装jestvscode支持jest的智能提示创建JS测试用例 安装yarn yarn是meta发布的一款取代npm的包管理工具。 npm install -g yarn查看yarn软件源 yarn config get registry换源 yarn config set registry https://registry.npmmirror.com恢复官方源 yarn co…

详细分析Spring Security OAuth2中的JwtAccessTokenConverter基本知识(附Demo)

目录 前言1. 基本知识2. Demo3. 实战 前言 java框架 零基础从入门到精通的学习路线 附开源项目面经等&#xff08;超全&#xff09;【Java项目】实战CRUD的功能整理&#xff08;持续更新&#xff09; 1. 基本知识 JwtAccessTokenConverter 是 Spring Security OAuth2 中的一…

【NoSQL】portswigger NoSQL注入 labs 全解

目录 NoSQL NoSQL 数据库模型 NoSQL 注入的类型 NoSQL 语法注入 检测 MongoDB 中的语法注入 lab1:检测 NoSQL 注入 NoSQL 运算符注入 提交查询运算符 检测 MongoDB 中的运算符注入 lab2:利用 NoSQL 运算符注入绕过身份验证 利用语法注入来提取数据 MongoDB 中的数据…

华为---MUX VLAN简介及示例配置

目录 1. 产生背景 2. 应用场景 3. 主要功能 4. 基本概念 5. 配置步骤及相关命令 6.示例配置 6.1 示例场景 6.2 网络拓扑图 6.3 配置代码 6.4 配置及解析 6.5 测试验证 配置注意事项 1. 产生背景 MUX VLAN&#xff08;Multiplex VLAN&#xff09;提供了一种通过VLA…

【C++力扣】917.仅仅反转字母|387.字符串中第一个唯一字符|415.字符串相加

✨ Blog’s 主页: 白乐天_ξ( ✿&#xff1e;◡❛) &#x1f308; 个人Motto&#xff1a;他强任他强&#xff0c;清风拂山冈&#xff01; &#x1f525; 所属专栏&#xff1a;C深入学习笔记 &#x1f4ab; 欢迎来到我的学习笔记&#xff01; 一、917.仅仅反转字母 1.1 题目描述…

VMware tools菜单为灰色无法安装

这个工具之前为灰色&#xff0c;无法安装&#xff0c;导致无法实现跟主机的共享文件夹等操作。极为不便。 根据其他教程提示&#xff1a;看到软件是这个配置。 修改为自动检测&#xff0c;tools就可以安装了。之前没注意到。 也有说dvd光盘也要设置。但是经过我测试。只设置软…

各省份消费差距(城乡差距)数据(2005-2022年)

消费差距&#xff0c;特别是城乡消费差距&#xff0c;是衡量一个国家或地区经济发展均衡性的重要指标。 2005年-2022年各省份消费差距&#xff08;城乡差距&#xff09;数据&#xff08;大数据&#xff09;.zip资源-CSDN文库https://download.csdn.net/download/2401_84585615/…

谷粒商城のRabbitMQ基础篇

文章目录 前言一、Rabbit MQ简介1、基本概念2、组件架构 二、使用步骤1.引入依赖2.application.properties3、docker 安装Rabbit MQ3、使用案例3.1、定义队列3.2、定义交换机3.3、绑定3.4、发送消息3.5、接受消息3.5、自定义消息序列化方式3.6、演示Fanout 交换机模式3.7、演示…

总结TypeScript相关知识

目录 引入认识特点安装使用变量声明类型推导 JS 和 TS 共有类型number类型boolean类型string类型Array类型null和undefined类型object类型symbol类型对象类型函数类型 可选和只读type 和 interface索引签名类型断言非空类型断言类型缩小严格赋值检测现象TS 新增类型字面量类型a…

[统计分析] 出现典型锯齿图的一种情况;资源泄露

接上回说&#xff0c;https://mzhan017.blog.csdn.net/article/details/142689870&#xff1b; 在问题分析的过程中发现产品里的一个统计计数出现了下面的锯齿型。而这个问题的表象之一是每隔一段时间&#xff0c;业务程序重启。所以产生这个锯齿形的原因之一就是业务程序重启&…

【C++ STL算法】二分查找 lower_bound、upper_bound、equal_range、binary_search

文章目录 【 1. 首个不小于 lower_bound 】【 2. 首个大于 upper_bound 】【 3. 所有等于 equel_range 】【 4. 二分查找 binary_search 】 当 指定区域内的数据处于有序状态 时&#xff0c;如果想查找某个目标元素&#xff0c;更推荐使用二分查找的方法&#xff08;相比顺序查…

openpnp - juki吸嘴尺寸

文章目录 openpnp - juki吸嘴尺寸概述笔记吸嘴可以对应的最小元件尺寸END openpnp - juki吸嘴尺寸 概述 在网上买的juki吸嘴的商品页面&#xff0c;并没有具体的吸嘴尺寸。 现在贴片时&#xff0c;要根据吸嘴外径大小来决定具体元件要用哪种吸嘴&#xff0c;先自己量一下。 …