可以在POST Json中附加文件吗?

时间:2021-03-29 17:02:25

I have a heap of data in format JSON(Serialized object). I send this data to server by POST method with header: Content-Type: application/json.

我有一堆格式为JSON(序列化对象)的数据。我用header: Content-Type: application/json的POST方法将数据发送到服务器。

Is it possible to attach file to body request and send at once. Or JSON data sugggests sending only text data?

是否可以将文件附加到正文请求并立即发送。还是JSON数据建议只发送文本数据?

2 个解决方案

#1


3  

In this context, the content-type header aims to describe the type of data in the request body. If you use application/json the server will expect a JSON body.

在此上下文中,content-type header旨在描述请求体中的数据类型。如果您使用application/json,服务器将期望得到json体。

If your goal is to send a single request with a JSON object and a file, you can either encode the file in the JSON structure (Probably base64. See: Binary Data in JSON String. Something better than Base64)

如果您的目标是发送一个带有JSON对象和文件的请求,那么您可以将该文件编码为JSON结构(可能是base64)。参见:JSON字符串中的二进制数据。比Base64)

{
  ...
  file: "encoded_content",
  ...
}

Or you can use the content type multipart/form-data. A multipart is a part containing other part. The first subpart may be the JSON strucuture. The second one may be the file

也可以使用内容类型multipart/form-data。多部分是包含其他部分的部分。第一部分可能是JSON结构。第二个可能是文件

#2


0  

Try to send the file inside the json object as a base64 string:

尝试将该文件作为base64字符串发送到json对象中:

{
"file":"dGhpcyBpcyBhIGZpbGUgc2FtcGxl..." 
}

Later you can open the file with something like:

之后,您可以用以下方式打开文件:

document.location = 'data:application/pdf;base64,' + file

#1


3  

In this context, the content-type header aims to describe the type of data in the request body. If you use application/json the server will expect a JSON body.

在此上下文中,content-type header旨在描述请求体中的数据类型。如果您使用application/json,服务器将期望得到json体。

If your goal is to send a single request with a JSON object and a file, you can either encode the file in the JSON structure (Probably base64. See: Binary Data in JSON String. Something better than Base64)

如果您的目标是发送一个带有JSON对象和文件的请求,那么您可以将该文件编码为JSON结构(可能是base64)。参见:JSON字符串中的二进制数据。比Base64)

{
  ...
  file: "encoded_content",
  ...
}

Or you can use the content type multipart/form-data. A multipart is a part containing other part. The first subpart may be the JSON strucuture. The second one may be the file

也可以使用内容类型multipart/form-data。多部分是包含其他部分的部分。第一部分可能是JSON结构。第二个可能是文件

#2


0  

Try to send the file inside the json object as a base64 string:

尝试将该文件作为base64字符串发送到json对象中:

{
"file":"dGhpcyBpcyBhIGZpbGUgc2FtcGxl..." 
}

Later you can open the file with something like:

之后,您可以用以下方式打开文件:

document.location = 'data:application/pdf;base64,' + file