javascript 多部分 HTTP 响应

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/47067312/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 07:10:08  来源:igfitidea点击:

Multipart HTTP response

javascriptnode.jsservermultiparthapijs

提问by Seth Holladay

The goal is for a Node.js / hapiAPI server to respond to a browser's AJAX request with two things:

目标是让 Node.js / hapiAPI 服务器通过两件事来响应浏览器的 AJAX 请求:

  • A media file (e.g. an image)
  • A JSON object with metadata about the file
  • 媒体文件(例如图像)
  • 带有文件元数据的 JSON 对象

These are two separate items only because binary data cannot easily be stored in JSON. Otherwise, this would be a single resource. Nevertheless, it is preferable that they be sent in a single response.

这是两个单独的项目,因为二进制数据不容易存储在 JSON 中。否则,这将是单个资源。然而,最好在单个响应中发送它们。

We upload these in a single request with multipart/form-data. In that case, browsers provide a built-in mechanism to serialize the body and most server-side frameworks know how to parse it. But how does one do the same for a response, in the opposite direction?Namely, how should a server serialize the body to transmit it to a client?

我们在单个请求中上传这些文件multipart/form-data。在这种情况下,浏览器提供了一种内置机制来序列化主体,并且大多数服务器端框架都知道如何解析它。但是,如何以相反的方向对响应做同样的事情呢?即,服务器应该如何序列化正文以将其传输到客户端?

From what I can tell, multipart/mixedcould be a useful content type. But there is very little talk of this. Most people seem to resort to providing two separate GETroutes, one for each piece. I dislike that because it opens you up to race conditions, amongst other things. What am I missing?

据我所知,multipart/mixed可能是一种有用的内容类型。但是很少有人谈论这个。大多数人似乎求助于提供两条独立的GET路线,每条路线。我不喜欢这样,因为它会让你面临竞争条件等问题。我错过了什么?

See also my question in hapijs/discuss#563.

另请参阅hapijs/discuss#563 中我的问题。

回答by guest271314

You can serve the response as multipart/form-dataand use Response.formData()to read response at client

您可以将响应作为响应multipart/form-data并用于Response.formData()在客户端读取响应

fetch("/path/to/server", {method:"POST", body:formData})
.then(response => response.formData())
.then(fd => {
  for (let [key, prop] of fd) {
    console.log(key, prop)
  }
})

let fd = new FormData();
fd.append("json", JSON.stringify({
  file: "image"
}));
fetch("data:image/gif;base64,R0lGODlhEAAQAPIAAP///wAAAMLCwkJCQgAAAGJiYoKCgpKSkiH+GkNyZWF0ZWQgd2l0aCBhamF4bG9hZC5pbmZvACH5BAAKAAAAIf8LTkVUU0NBUEUyLjADAQAAACwAAAAAEAAQAAADMwi63P4wyklrE2MIOggZnAdOmGYJRbExwroUmcG2LmDEwnHQLVsYOd2mBzkYDAdKa+dIAAAh+QQACgABACwAAAAAEAAQAAADNAi63P5OjCEgG4QMu7DmikRxQlFUYDEZIGBMRVsaqHwctXXf7WEYB4Ag1xjihkMZsiUkKhIAIfkEAAoAAgAsAAAAABAAEAAAAzYIujIjK8pByJDMlFYvBoVjHA70GU7xSUJhmKtwHPAKzLO9HMaoKwJZ7Rf8AYPDDzKpZBqfvwQAIfkEAAoAAwAsAAAAABAAEAAAAzMIumIlK8oyhpHsnFZfhYumCYUhDAQxRIdhHBGqRoKw0R8DYlJd8z0fMDgsGo/IpHI5TAAAIfkEAAoABAAsAAAAABAAEAAAAzIIunInK0rnZBTwGPNMgQwmdsNgXGJUlIWEuR5oWUIpz8pAEAMe6TwfwyYsGo/IpFKSAAAh+QQACgAFACwAAAAAEAAQAAADMwi6IMKQORfjdOe82p4wGccc4CEuQradylesojEMBgsUc2G7sDX3lQGBMLAJibufbSlKAAAh+QQACgAGACwAAAAAEAAQAAADMgi63P7wCRHZnFVdmgHu2nFwlWCI3WGc3TSWhUFGxTAUkGCbtgENBMJAEJsxgMLWzpEAACH5BAAKAAcALAAAAAAQABAAAAMyCLrc/jDKSatlQtScKdceCAjDII7HcQ4EMTCpyrCuUBjCYRgHVtqlAiB1YhiCnlsRkAAAOwAAAAAAAAAAAA==")
  .then(response => response.blob())
  .then(blob => {
    fd.append("file", blob);
    new Response(fd)
      .formData()
      .then(formData => {
        for (let [key, data] of formData) {
          console.log(key, data)
        }
      })
  })

回答by Evert

If you are going for a multipart format, I don't think there's anything inherently wrong with using the exact same format both during upload (POST/PUT) and retrieval (GET).

如果您要使用多部分格式,我认为在上传 (POST/PUT) 和检索 (GET) 期间使用完全相同的格式没有任何本质上的错误。

I think there's definitely an elegance in using the same on-wire format in both directions when working with HTTP.

我认为在使用 HTTP 时在两个方向上使用相同的在线格式绝对是一种优雅。

However, if you want to send form-data during PUT/POST and JSON back using GET, then I would start questioning whether this is the right thing to do.

但是,如果您想在 PUT/POST 和 JSON 期间使用 GET 发送表单数据,那么我会开始质疑这是否是正确的做法。

multipart gets annoying for clients if they just want to display the image. Have you considered just using different endpoints; one for the image and one for it's meta-data? What reason do you have to want to combine them into a single resource?

如果客户只想显示图像,multipart 会让客户感到厌烦。您是否考虑过仅使用不同的端点;一个用于图像,另一个用于元数据?您有什么理由要将它们合并为一个资源?

Alternatively, you could also attempt to embed the information in the image. JPEG for instance allows custom data to be added using EXIF. At least you preserve the ability to just open the image directly.

或者,您也可以尝试在图像中嵌入信息。例如,JPEG 允许使用 EXIF 添加自定义数据。至少您保留了直接打开图像的能力。

However, I will conclude with saying that multipart/mixedis appropriate if you just want to embed an image + a json object, but bear in mind:

但是,multipart/mixed如果您只想嵌入图像 + json 对象,我会说这是合适的,但请记住:

  1. It's probably a bit inconvenient for consumption
  2. It's also a bit unusual
  3. I'm fairly sure that multipart encoding will require you to encode your image in some 7bit encoding, which will inherently cause the request size to blow up quite a bit.
  1. 可能消费有点不方便
  2. 也有点不寻常
  3. 我相当确定多部分编码将要求您以某种 7 位编码对图像进行编码,这本身会导致请求大小大幅增加。