是否存在“良好实践”?不依赖FormData发送文件的方法?
我目前正在开发一个具有 React Native 前端和 Node.js/Express 后端的应用程序。我完全能够使用 FormData 和 Content-Type multipart/form-data 上传文件。我遇到的问题是,当使用 FormData 时,您希望在请求正文中发送的任何其他数据都必须转换为字符串。当简单地发送 JS 对象作为请求正文时,情况并非如此(当然,只要您在后端解析它)。我想知道是否有一种好的实践方法可以在请求中与 JSON 一起发送一个或多个文件,而不会丢失所述 JSON 的类型?
谢谢
I'm currently working on an app with a React Native front-end and Node.js/Express backend. I am perfectly able to upload files using FormData with Content-Type multipart/form-data. The problem I have is that when using FormData, any other data that you wish to send in the body of the request is necessarily converted to a string. This isn't the case when one simply sends a JS object as the body of the request (as long you parse it on the backend of course). I wish to know if there is a good-practice way to send a file/files alongside JSON in a request, without losing the typings of said JSON?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
当您坚持将图像与 JSON 中的其他数据一起发送时,据我所知,您唯一的选择是将图像转换为可以通过 JSON 传输的某种数据类型。
最明显的选择是字符串,这里通常使用的是 base64 编码。然而,它的效率不是很高,并且可能会导致滞后。
有时为了保持在 JSON 域内但仍然能够上传图像,需要创建两个端点。一种用于 JSON 数据。一种用于以二进制格式上传图像。
When you insist on sending the image along with other data inside the JSON, then AFAIK your only option is to convert the image to some data type which can be transmitted via JSON.
The most obvious choice would be a string, and what is usually used here is the base64 encoding. It is, however, not very efficient and can cause lag.
What is sometimes done to stay within the JSON domain but still being able to upload images is to create two endpoints. One for the JSON data. One for the image upload in a binary format.
将数据以 JSON 形式添加到 FormData 的字段中:
Add your data as JSON in a field of the FormData: