英文:
REST API for uploading file inside JSON
问题
我正在设计一个 REST API,用于上传一个较大的文件(100MB)以及一些信息。所以自然而然地会考虑使用 JSON 编码。
可以像这样设计:
{
file: 文件内容或 URL?
name: 字符串
description: 字符串
}
name 和 description 可以很容易地使用 JSON 处理,但我不确定如何将文件内容添加到其中。
此外,我在考虑是否应该使用 HTTP PUT 方法。这样做正确吗?
顺便提一下,如果有关系的话,这个 API 是使用 Golang 实现的。
英文:
I am designing an REST API to upload a largish (100MB) file together with some information. So it's natural to think of json encoding.
So something like this:
{
file: content of the file or URL?
name: string
description: string
}
The name and description are easy to do with json but I'm not sure how the file content can be added to it.
Also I'm thinking I should use http PUT method. Is this correct?
Incidentally, golang is used to implement this API if it matters.
答案1
得分: 3
对于JSON编码,使用[]byte
值来保存文件内容。标准的encoding/json包将[]byte
值编码为base64字符串。
以下是实现JSON编码的草图。声明一个表示有效负载的类型:
type Upload struct {
Name string
Description string
Content []byte
}
将文件编码为请求体:
v := Upload{Name: fileName, Description: description, Content: content}
var buf bytes.Buffer
if err := json.NewEncoder(&buf).Encode(v); err != nil {
// 处理错误
}
req, err := http.NewRequest("PUT", url, &buf)
if err != nil {
// 处理错误
}
resp, err := http.DefaultClient.Do(req)
在服务器上从请求体解码:
var v Upload
if err := json.NewDecoder(req.Body).Decode(&v); err != nil {
// 处理错误
}
另一个选项是使用mime/multipart包。与JSON编码相比,多部分编码更高效,因为不需要对文件进行base64或其他文本编码。
英文:
For a JSON encoding, use a []byte
value to hold the file contents. The standard encoding/json package encodes []byte
values as base64 strings.
Here's a sketch of how to implement the JSON encoding. Declare a type representing the payload:
type Upload struct {
Name string
Description string
Content []byte
}
To encode the file to a request body:
v := Upload{Name: fileName, Description: description, Content: content}
var buf bytes.Buffer
if err := json.NewEncoder(&buf).Encode(v); err != nil {
// handle error
}
req, err := http.NewRequest("PUT", url, &buf)
if err != nil {
// handle error
}
resp, err := http.DefaultClient.Do(req)
To decode the from a request body on the server:
var v Upload
if err := json.NewDecoder(req.Body).Decode(&v); err != nil {
// handle error
}
Another option is to use the mime/multipart package. The multipart encoding will be more efficient than JSON encoding because no base64 or other text encoding of the file is required for multipart.
答案2
得分: 0
对我来说,最明确的方法是以某种方式对文件字节进行编码。base64似乎是一个不错的选择,并且golang内置了对它的支持,使用"encoding/base64"包即可。
英文:
To me, the most clear-cut way to do it would be to encode the file bytes somehow. base64 seems like a good choice, and golang has built-in support for it with "encoding/base64".
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论