简体   繁体   English

如何将文件从客户端上传到服务器,然后从服务器上传到服务器

[英]How to upload a file from client to server and then server to server

In my web application I need to upload the files.I have used axios to send file as requests from client to server(api) with form data append and also necessary headers.Now the ask is that I have to pass the file from server(api) to another endpoint api.Since I am using next.js,both client and server api handling is done from my side在我的 web 应用程序中,我需要上传文件。我使用 axios 将文件作为客户端请求发送到服务器(api),表单数据为 append 以及必要的标头。现在的问题是我必须从服务器传递文件( api) 到另一个端点 api。由于我使用的是 next.js,客户端和服务器 api 处理都是从我这边完成的

The client request is fine with binary data and all.But I don't know how to pass it from the server(api) to another server(api) using axios with the request got from client.As this is a very unusual requirement, there are no available solutions in online.客户端请求可以使用二进制数据和所有数据。但是我不知道如何使用 axios 将它从服务器(api)传递到另一个服务器(api)以及从客户端获得的请求。因为这是一个非常不寻常的要求,在线没有可用的解决方案。

I would be glad if I can have some solution or an implementation如果我能有一些解决方案或实施,我会很高兴

import axios from 'axios';

async function sendFileToEndpoint(file) {
  try {
    const formData = new FormData();
    formData.append('file', file);

    const response = await axios.request({
      method: 'POST',
      url: 'http://endpoint-api.com/upload',
      headers: {
        'Content-Type': 'multipart/form-data',
      },
      data: formData,
    });
    console.log(response);
  } catch (error) {
    console.error(error);
  }
}

In this example, the sendFileToEndpoint function accepts a file as an argument and sends it to the endpoint API using a POST request with multipart/form-data content type.在此示例中, sendFileToEndpoint function 接受一个文件作为参数,并使用内容类型为multipart/form-data的 POST 请求将其发送到端点 API。 You can adjust the request options as needed to meet the requirements of the endpoint API.您可以根据需要调整请求选项以满足端点 API 的要求。

It's up to you to manage the server.由您来管理服务器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM