简体   繁体   English

在节点js中从客户端向服务器端发送图像

[英]sending an image from client to server-side in node js

I am trying to upload an image to the server but keep getting an error in the chrome console "POST http://localhost:3000/images 500 (Internal Server Error) @ main.js:19". 我正在尝试将图像上传到服务器,但在Chrome控制台“POST http:// localhost:3000 / images 500(内部服务器错误)@ main.js:19”中继续出错。

it looks like he server side of my application is not receiving the image.when I try to access the file on the server I get undefined([Error: Input file is missing]). 看起来我的应用程序的服务器端没有接收到图像。当我尝试访问服务器上的文件时,我得到未定义([错误:输入文件丢失])。 When I post using html without the client-side javascript, the image is posted successfully. 当我使用没有客户端javascript的html发布时,图像成功发布。 However, I want to post the image using the client-side js. 但是,我想使用客户端js发布图像。 Can someone help me know what I am doing wrong 有人能帮助我知道我做错了什么

main.js main.js

const form = document.querySelector('form')

form.addEventListener('submit', e => {
e.preventDefault()

const files = document.querySelector('[type=file]').files
let req = new XMLHttpRequest();
const formData = new FormData()


let file = files[0]
console.log((file));
formData.append('files[]', file)

req.open("POST", 'http://localhost:3000/images');
req.setRequestHeader('Content-Type', 'image/*');
req.setRequestHeader('Accept', 'image/*');
req.send(formData);
});

index.html 的index.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial- 
scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />

<title>Upload Files</title>
</head>

<body>
<form enctype="multipart/form-data">
  <input type="file" name="files[]" multiple />
  <button type="submit" class="btn btn-primary text-center" 
id="queryButton"> Query </button>
</form>

<script src="main.js"></script>
</body>
</html>

You're appending files[] as an array in a FormData object, but you're setting the request content-type to image/* . 您将files[]作为数组附加到FormData对象中,但是您将请求内容类型设置为image/* In other words, you're telling the server you're sending an image, but you're actually sending form data, which is not the same format. 换句话说,您告诉服务器您正在发送图像,但实际上您发送的表单数据格式不同。

I don't think you need to set the content-type; 我认为你不需要设置内容类型; when you send a FormData object, the XHR will set the type correctly on its own. 当您发送FormData对象时,XHR将自己正确设置类型。 So try removing the content-type header completely. 因此,请尝试完全删除内容类型标头。 If that doesn't work, try using a content-type of multipart/form-data instead. 如果这不起作用,请尝试使用内容类型的multipart/form-data

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM