如何将多部分文件从另一个服务发送到一个服务

2024-05-09

我有两个端点 api,它们是/uploadand /重定向

/upload是我直接上传文件的地方。/重定向是我接收文件并将其传递给上传并获取 JSON 响应的地方/upload.所以下面是我的代码:

package com.example;

import java.io.BufferedOutputStream;

import java.io.File;
import java.io.FileOutputStream;
import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

@RestController
public class UserLogsController {

    @Autowired
    @Qualifier("restTemplateUserRegitration")
    private RestTemplate restTemplateUserRegitration;

    @Bean
    public RestTemplate restTemplateUserRegitration() {

        RestTemplateBuilder builderUserRegitration = new RestTemplateBuilder();
        RestTemplate buildUserRegitration = builderUserRegitration.build();

        return buildUserRegitration;
    }

    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    public @ResponseBody ResponseEntity<Map<String, Object>> handleFileUpload(
            @RequestParam("file") MultipartFile file) {
        String name = file.getName();
        System.out.println(name);
        if (!file.isEmpty()) {
            try {
                byte[] bytes = file.getBytes();
                BufferedOutputStream stream = new BufferedOutputStream(
                        new FileOutputStream(new File("D:\\myfile.csv")));
                stream.write(bytes);
                stream.close();

                JwtAuthenticationErrorResponse FeedBackResponse = new JwtAuthenticationErrorResponse();
                FeedBackResponse.setCode(100);
                FeedBackResponse.setMessage("Successfully Updated Batch User List");
                Map<String, Object> FeedBackStatus = new HashMap<String, Object>();
                FeedBackStatus.put("status", FeedBackResponse);
                return ResponseEntity.ok(FeedBackStatus);

            } catch (Exception e) {
                JwtAuthenticationErrorResponse FeedBackResponse = new JwtAuthenticationErrorResponse();
                FeedBackResponse.setCode(100);
                FeedBackResponse.setMessage(e.getMessage());
                Map<String, Object> FeedBackStatus = new HashMap<String, Object>();
                FeedBackStatus.put("status", FeedBackResponse);
                return ResponseEntity.ok(FeedBackStatus);
            }
        } else {
            JwtAuthenticationErrorResponse FeedBackResponse = new JwtAuthenticationErrorResponse();
            FeedBackResponse.setCode(100);
            FeedBackResponse.setMessage("Successfully Updated Batch User List");
            Map<String, Object> FeedBackStatus = new HashMap<String, Object>();
            FeedBackStatus.put("status", FeedBackResponse);
            return ResponseEntity.ok(FeedBackStatus);
        }
    }

    @RequestMapping(value = "/redirect", produces = { MediaType.APPLICATION_JSON_VALUE }, method = RequestMethod.POST)
    public ResponseEntity<?> registerBatchUser(@RequestParam("file") MultipartFile file) {

        Map<String, Object> FeedBackStatus = new HashMap<String, Object>();
        FeedBackStatus = restTemplateUserRegitration.postForObject("http://localhost:8080/upload", file, Map.class);
        return ResponseEntity.ok(FeedBackStatus);

    }

}

端点 /upload 工作得很好。但是当我调用 /redirect 时,它会抛出一个错误

“例外”: “org.springframework.http.converter.HttpMessageNotWritableException”, "message": "无法写入 JSON 文档:找不到序列化器 类 java.io.FileDescriptor 且未发现要创建的属性 BeanSerializer(为了避免异常,禁用 SerializationFeature.FAIL_ON_EMPTY_BEANS)(通过引用链: org.springframework.web.multipart.support.StandardMultipartHttpServletRequest$StandardMultipartFile["inputStream"]->java.io.FileInputStream["fd"]); 嵌套异常是 com.fasterxml.jackson.databind.JsonMappingException:没有序列化器 找到了类 java.io.FileDescriptor 并且没有发现任何属性 创建 BeanSerializer (为了避免异常,禁用 SerializationFeature.FAIL_ON_EMPTY_BEANS)(通过引用链: org.springframework.web.multipart.support.StandardMultipartHttpServletRequest$StandardMultipartFile["inputStream"]->java.io.FileInputStream["fd"])",

我不确定为什么会发生这种情况。如有任何帮助,我们将不胜感激。


这就成功了

@RequestMapping(value = "/redirect", produces = { MediaType.APPLICATION_JSON_VALUE }, method = RequestMethod.POST)
    public ResponseEntity<?> registerBatchUser(@RequestParam("file") MultipartFile file) {
       if (!file.isEmpty()) {
            try {
                byte[] bytes = file.getBytes();
                BufferedOutputStream stream = new BufferedOutputStream(
                        new FileOutputStream(new File("D:\\myfileredirect.csv")));
                stream.write(bytes);
                stream.close();


            } catch (Exception e) {
                JwtAuthenticationErrorResponse FeedBackResponse = new JwtAuthenticationErrorResponse();
                FeedBackResponse.setCode(100);
                FeedBackResponse.setMessage(e.getMessage());
                Map<String, Object> FeedBackStatus = new HashMap<String, Object>();
                FeedBackStatus.put("status", FeedBackResponse);
                return ResponseEntity.ok(FeedBackStatus);
            }
        MultiValueMap<String, Object> parameters = new LinkedMultiValueMap<String, Object>();
        parameters.add("file", new FileSystemResource("D:\\myfileredirect.csv")); 
        HttpHeaders headers = new HttpHeaders();
        headers.set("Content-Type", "multipart/form-data");



        Map<String, Object> FeedBackStatus=new HashMap<String, Object>();
        FeedBackStatus =  restTemplateUserRegitration.exchange("http://localhost:8080/upload",  HttpMethod.POST,  new HttpEntity<MultiValueMap<String, Object>>(parameters, headers), Map.class).getBody();
        return ResponseEntity.ok(FeedBackStatus);

    }

所以我所做的基本上是收集文件重写它,然后转换为 MultiValueMap 并发送到服务。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何将多部分文件从另一个服务发送到一个服务 的相关文章

随机推荐

  • 如何制作具有移动外观的 emberjs 应用程序(如 jquery mobile 中的应用程序)?

    我有一个使用 Emberjs 的简单移动 Web 应用程序项目 对于外观和感觉 我想要类似于 JQuery Mobile 的东西 有没有办法混合使用 Emberjs 和 jquery mobile 如果是这样 怎么办 我查看了 Travis
  • createRadialGradient 和透明度

    我正在玩createRadialGradient 在 HTML5 画布上 它就像一个魅力 除非我试图实现 半 透明 我制作了这个 jsFiddle 是为了让事情变得更清晰 http jsfiddle net rfLf6 1 http jsf
  • #pragma pack(16) 和 #pragma pack(8) 的效果总是相同吗?

    我正在尝试使用来对齐数据成员 pragma pack n http msdn microsoft com en us library 2e70t5y1 28v vs 100 29 aspx 以下面为例 include
  • 装饰器不支持函数调用

    我在 ng build prod 时遇到问题 装饰器不支持函数调用 但在 initialState 中调用了 Ui export const initialState AppState userAisles null userItems n
  • SSIS ForEach File 循环 - 将文件名插入表

    我正在构建一个 SSIS 包 使用 VS 2017 来从特定文件夹加载一堆 CSV 文件 使用 ForEach File 循环效果很好 数据流任务具有平面文件源和 OLE DB 目标 我希望能够将文件名以及 CSV 文件中的数据保存在同一个
  • 如何使用 Ansible when 条件在文件中搜索字符串

    我有一个变量中用 n 分隔的搜索字符串列表listofips 我想在文件中搜索该字符串hello csv在我的下面playbook dir 我可能遇到一些语法问题 我不确定 但下面是我尝试过的 set fact listofips 10 0
  • Jupyter Notebook 中的多处理与线程

    我试图测试这个例子here https ipywidgets readthedocs io en stable examples Widget 20Asynchronous html将其从线程更改为多处理 在 jupyter Noteboo
  • 使用“each”关键字将“列表”传递给函数调用

    首先 我承认我不是 M 或 Power Query 专家 尽管我确实有一些 Power BI 经验 我正在尝试开发一个股票投资组合 该投资组合将跟踪定制的 股票列表及其价格历史记录和其他指标 由于我试图解决的问题 我的部分代码基于以下博客
  • QuickFIX - 设置开始时间\结束时间

    QuickFIX http www quickfixengine org has a 配置文件 http www quickfixengine org quickfix doc html configuration html你设置的地方St
  • 纯虚函数可能没有内联定义。为什么?

    纯虚函数是那些虚函数并且具有纯说明符 0 第 10 4 条第 2 款C 03 的内容告诉我们什么是抽象类 顺便说一句 如下 注意 函数声明不能 同时提供纯说明符和定义 尾注 示例 struct C virtual void f 0 ill
  • 在 Java 服务器中验证 Windows 用户

    我正在开发一个用 Java 编写的服务器和一个在同一网络上的 Windows 计算机上运行的客户端 用 Net 编写的桌面应用程序 我希望进行一些基本身份验证 以便服务器可以确定运行客户端的用户的用户名 而不需要用户在客户端中重新输入其 W
  • 为什么从 ASP.NET 页面调用的 DLL 中出现异常后,我的 IIS7 应用程序池会关闭?

    我已阅读帖子ASP NET应用程序池关闭问题 https stackoverflow com questions 4742122 asp net application pool shutdown problem and IIS 7 5 应
  • django模板中获取用户信息

    从 django 模板获取用户信息的最佳方法是什么 例如 如果我只想 如果用户已登录 则显示 欢迎 用户名 否则 显示登录按钮 我正在使用 django 注册 身份验证 当前 Django 版本的替代方法 if user is authen
  • CodeIgniter:使用多维 POST 数据验证表单

    所以框架是CodeIgniter 2 0 2 我有一个表单 其中包含与数据库中的行相对应的字段组 字段名称的格式为 opt 0 foo opt 0 bar opt 1 foo opt 1 bar etc 索引 1 2等 并不对应于数据库中的
  • 如何检查摘要周期是否稳定(又名“Angular 完成编译了吗?”)

    tl dr 最初的问题是 如何在每个摘要周期触发回调 但潜在的问题更有趣 因为这回答了两个问题 所以我继续修改了标题 Context 在解决了所有依赖项 nginclude API 调用等之后 我试图控制 Angular 何时完成 HTML
  • SQL Server 数据库中的表具有互斥外键的最佳实践

    在这里 我正在寻找针对以下问题的优缺点的最佳解决方案 Entity1 E1 pk 与其他不同的列 Entity2 E2 pk 与其他不同的列 Entity3 E3 pk 与其他不同的列 我需要创建之间的关系Entity1 and Entit
  • 从 oracle 中为每个组选择最新行

    我在留言簿中有一张包含用户评论的表格 列有 id user id 标题 评论 时间戳 我需要为每个用户选择最新行 我尝试使用 group by 执行此操作 但没有管理它 因为我无法在按 user id 分组的同一查询中选择任何其他内容 SE
  • Loopback 中的动态模型

    如何在环回中创建动态模型 而不是对所有模型使用命令 lb model 例如 如果我想创建 30 个具有几乎相同属性的模型 那么会遇到一次又一次创建所有 30 个模型和那些相应属性的麻烦 是否可以创建模型并使用环回将其迭代到另一个模型 请分享
  • ASP.NET Core Razor Page 多路径路由

    我正在使用 ASP NET Core 2 0 Razor Pages 不是 MVC 构建系统 但在为页面添加多个路由时遇到问题 例如 所有页面都应该能够通过 abc com language 访问segment shop mypage 或
  • 如何将多部分文件从另一个服务发送到一个服务

    我有两个端点 api 它们是 uploadand 重定向 upload是我直接上传文件的地方 重定向是我接收文件并将其传递给上传并获取 JSON 响应的地方 upload 所以下面是我的代码 package com example impo