initial
This commit is contained in:
commit
74ae93a96e
1 changed files with 94691 additions and 0 deletions
|
|
@ -0,0 +1,106 @@
|
|||
file upload as body directly
|
||||
|
||||
We need to pipe the data to writestream for this
|
||||
|
||||
```js
|
||||
const express = require("express");
|
||||
const fs = require("fs");
|
||||
const app = express();
|
||||
const port = 8090;
|
||||
|
||||
app.use(express.json({ limit: "10mb" })); // Adjust the limit as needed
|
||||
app.use(express.static(__dirname + "/public"));
|
||||
|
||||
// Handle PUT request with file in the request body
|
||||
app.put("/upload", (req, res) => {
|
||||
console.log("body: ", req.body);
|
||||
console.log("file: ", req.files);
|
||||
|
||||
const wsStream = fs.createWriteStream("uploads/name.mp3");
|
||||
|
||||
req.pipe(wsStream);
|
||||
|
||||
req.on("end", () => {
|
||||
wsStream.close(() => {
|
||||
res.json({ data: "success" });
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
});
|
||||
|
||||
app.listen(port, () => {
|
||||
console.log(`Server is running on port ${port}`);
|
||||
});
|
||||
|
||||
```
|
||||
|
||||
Front end
|
||||
```html
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Document</title>
|
||||
</head>
|
||||
<body>
|
||||
<input type="file" name="" value="">
|
||||
<button>Submit</button>
|
||||
|
||||
<script>
|
||||
|
||||
const convertToFormData=(obj)=>{
|
||||
const formData=new FormData()
|
||||
for(let prop in obj){
|
||||
|
||||
if (obj[prop] instanceof File) {
|
||||
formData.append(prop, obj[prop], obj[prop].name);
|
||||
}
|
||||
else {
|
||||
formData.append(prop, obj[prop]);
|
||||
}
|
||||
}
|
||||
|
||||
return formData
|
||||
}
|
||||
const fileEle=document.querySelector("input")
|
||||
const button=document.querySelector("button")
|
||||
button.addEventListener("click",()=>{
|
||||
// const url="http://localhost:8085/post"
|
||||
// const encodedURL=encodeURIComponent(url)
|
||||
// const proxyURL='http://localhost:8080/cors-submit'
|
||||
|
||||
// const fetchurl=`${proxyURL}?url=${encodedURL}`
|
||||
|
||||
const fetchurl='upload'
|
||||
|
||||
const fileInput=fileEle.files[0]
|
||||
|
||||
const obj={
|
||||
username: 'hey',
|
||||
pass: '123',
|
||||
fileInput
|
||||
}
|
||||
|
||||
fetch(fetchurl,{
|
||||
method : 'PUT',
|
||||
mode: 'cors',
|
||||
headers: {
|
||||
//'Content-Type' : "multipart/form-data",
|
||||
},
|
||||
body : fileInput
|
||||
})
|
||||
.then(res=>res.json())
|
||||
.then(data=>{
|
||||
console.log('data: ',data)
|
||||
})
|
||||
.catch(err=>{
|
||||
console.log('err: ',err)
|
||||
})
|
||||
|
||||
} )
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
```
|
||||
Loading…
Reference in a new issue