简体   繁体   中英

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".

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. However, I want to post the image using the client-side js. Can someone help me know what I am doing wrong

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

<!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/* . 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. So try removing the content-type header completely. If that doesn't work, try using a content-type of multipart/form-data instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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