node.js - 使用 POST 将文件从 HTML5 网页上传到 Node.js 服务器
问题描述
亲爱的,
我想使用基于 HTML5 和 Node.js 的服务器来实现文件上传网页。另外我不想在客户端使用表单标签,我需要向服务器发送有关文件信息的额外数据。我使用自定义 HTTP 标头,以便服务器可以捕获它。
目前我的问题是客户端可以将文件上传到服务器,但服务器会保存带有附加数据的文件,例如 HTTP 标头和边界。
我认为服务器存储来自客户端的所有 HTTP 请求包括 HTTP 标头、文件二进制数据和边界等附加值。
我可以做些什么来只在服务器端存储文件数据?
服务器是使用 HTTP 模块实现的,目前我无法更改服务器的主模块,因为很多东西已经在服务器端实现了。
客户端 :
// HTML Code
<tr>
<td><textarea id="customData1"></textarea></td>
<td><textarea id="customData2"></textarea></td>
<td><input type="file" id="uploadFile"></td>
<td><button id="uploadFile" onclick="uploadFileToServer()">Upload</button</td>
</tr>
// JavaScript Code
function uploadFileToServer() {
var file = document.getElementById("uploadFile").files[0];
var uri = "/uploadFile";
var xhr = new XMLHttpRequest();
var fd = new FormData();
xhr.open("POST", uri, true);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
alert(xhr.responseText);
}
};
xhr.setRequestHeader("Content-Type", "multipart/form-data; boundary=\\\"Boundary\\\"");
xhr.setRequestHeader("my-custom-data-one", document.getElementById("customData1").value);
xhr.setRequestHeader("my-custom-data-two", document.getElementById("customData2").value);
xhr.setRequestHeader("file-size", file.size);
xhr.setRequestHeader("file-name", file.name);
fd.append("myFile", file);
xhr.send(fd);
}
</script>
我尝试了一些方法,但都不起作用。
服务器端 :
基本服务器代码)
http.createServer(function (req, res) {
if (req.method === 'POST') {
// Need to add upload file code
}
}).listen(PORT.Main);
案例 1) 使用附加块数据。但是也写入了无用的数据(标题/边界)。
req.on('data', function (data) {
console.log(data)
fs.appendFileSync(filename, data)// += data;
});
req.on('end', function () {
res.writeHead(200, { 'content-type': 'text/plain' })
res.write('Upload Complete!\n');
res.end();
});
案例 2) 使用 writeStream。但是也写入了无用的数据(标题/边界)。
var file = './temp.file'
var downloadWriteStream = fs.createWriteStream(file);
req.pipe(downloadWriteStream);
req.on('end', function () {
res.writeHead(200, { 'content-type': 'text/plain' })
res.write('Upload Complete!\n');
res.end();
});
案例3)使用强大的npm模块,但它返回错误消息:错误:MultipartParser.end():流意外结束:状态= START_BOUNDARY
var form = new formidable.IncomingForm();
form.parse(req);
form.on('fileBegin', function (name, file) {
file.path = filename;
});
form.on('file', function (name, file) {
console.log('Uploaded ' + file.name);
res.writeHead(200, { 'content-type': 'text/plain' })
res.write('Upload Complete!\n');
res.end();
});
感谢您阅读此问题,我期待您的回答。
解决方案
看看multer。它使这非常容易。
客户端示例代码:
<form action="/profile" method="post" enctype="multipart/form-data">
<input type="file" name="avatar" />
</form>
服务器示例代码:
var express = require('express')
var multer = require('multer')
var upload = multer({ dest: 'uploads/' })
var app = express()
app.post('/profile', upload.single('avatar'), function (req, res, next) {
// req.file is the `avatar` file
// req.body will hold the text fields, if there were any
})
推荐阅读
- typescript - Typescript 3.5 循环 HTMLCollectionOf
没完成 - java - FusionAuth OpenID 与 Azure AD 连接存在集成问题
- sql - SQL 探查器中是否有一种方法可以通过具有多个文本条件的 OR 条件的“TextData”过滤器进行过滤?
- jmeter - 如何将复合图插件与外部 jtl 或 csv 文件一起使用?
- javascript - 需要添加一个类来隐藏和显示元素一旦激活
- google-sheets - 谷歌表格 - 如何根据第一次出现的 X 检索列?
- go - Golang 解决hackerrank 的“对角线差”问题
- sql - 如何使用烧瓶更新 SQL Server 中的 varbinary(max) 列?
- perl - 带有引号(“”)的参数不会被转义
- c# - 使用 RSA-SHA256 签名