![](/img/trans.png)
[英]How to send image from [python client] to [node.js server] using tcp socket?
[英]How to send an image from the client to server in Node.js without saving the file
目前,我正在构建一个 web 应用程序,该应用程序使用 Node.js 并表示我的服务器端应用程序。 我对客户端-服务器应用程序还很陌生,不知道如何 go 将图像从我的客户端网站发送到我的快速服务器。 我想在图像到达服务器后对其进行处理,但我不想将文件存储在服务器上。 我的 index.html 中有一个file <input>
,我想将其用于客户端 select 他们的图像,但我不知道如何将其传递给服务器以用于处理的单独脚本中的变量图像并将计算结果发送回客户端。 非常感谢任何关于如何前进的建议!
我将用一个例子来解释它。 假设我想发送一所大学的图像,我想在某个地方的数据库中添加。 在我的表格中,我会:
<form action="" class='add-item-form'>
<input id='image-file' type='file'/>
<input type="submit" id="submitFormBtn"/>
</form>
现在,我们的想法是创建一个在单击 submitFormBtn 时激活的处理程序,使用反应或 vue,或 angular 或普通 javascript。这里有一个处理程序的示例:
function onSubmit() {
let input = document.querySelector("#image-file") as HTMLInputElement;
if(!!input.files){
// files is an array but e assume we only added one image
const file = input.files[0];
let reader = new FileReader();
// the reader triggers the functions whenever it's been loaded
reader.onload = function () {
// reader.results contains the binary string
// btoa converts the binary string into base64
//to ease data transportation through the wire
let base64_data = window.btoa(reader.result);
// service that makes the post request to the server
// implementations vary, I'd use axios library though
TeacherService.addUniversity(base64_data)
.then(res => {
// do something is it was a success
}).catch(err => {
// do something is it there was an error
}).finally(()=>{
// do someting either way
});
}
reader.readAsBinaryString(file);
}
}
现在,球在服务器上,您只需要一如既往地接收 json 并解码来自客户端的 base64 数据,根据您的服务器语言,有很多库可以做到这一点。 解码后,您使用适当的文件名及其文件扩展名保存文件,基本上就是这样,从那里您将在服务器中获得原始文件,您可以对其进行任何进一步处理。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.