说我有这个<input type="file" id="theFile">
我使用myVar =
document.getElementById('theFile').value
输出为console.log(myVar); // C:\fakepath\xxx.txt
然后我做一个简单的POST,有很多方法可以进行POST,但是一种基本的JavaScript方法是:
var http = new XMLHttpRequest();
http.onreadystatechange = function() {
http.open("POST", "http://localhost:port/upload-test");
http.setRequestHeader('Content-type', 'application/json');
var body = {
file: document.getElementById('theFile').value
}
http.send(JSON.stringify(body));
然后在我的Nodejs Express
服务中,我这样做:
app.post('/upload-test', (request, response) => {
console.log(request.body); // { file: 'C:\\fakepath\\xxx.txt' }
});
现在如何将文件保存到运行该服务的计算机上?
我知道诸如https://www.w3schools.com/nodejs/nodejs_uploadfiles.asp之类的其他解决方案,但这需要用户使用<form>
,这不是我想要的。我想使用基本的POST和JSON方法上传文件。
答案 0 :(得分:1)
请求的内容类型应该是multipart / form-data,因为您正在上传文件。 您可以使用multerjs进行nodejs上传
var express = require('express')
var multer = require('multer')
var upload = multer({ dest: 'uploads/' })
var app = express()
app.post('/upload-test', upload.single('avatar'), function (req, res, next) {
// req.file is the `avatar` file
// req.body will hold the text fields, if there were any
})
答案 1 :(得分:0)
客户端 首先,您需要将文件内容“读取”到变量中。您不能按照此处其他地方的说明直接上传文件。
我不确定您在使用什么客户端。例如。 React,Angular或纯Javascript。因此,这是指向SO上另一篇文章的链接,该文章有关如何选择客户端文件并将其内容读取到var中。 Read Client-Side file
一旦文件内容包含在var中,就可以将其“发布”。例如
// Build the Headers object.
let headers = new Headers();
headers.append("Content-Type","application/json");
// Build the body object.
let body = {
fileName: varContainingFileName,
fileContent: varContianingContentsOfFile
};
// Build the request
const response = await fetch(URL, {method: 'POST',
headers:headers,
body:JSON.stringify(body)});
// See what we get back from the service. Note, for the await to work,
// Needs to be wrapped in async method.
console.log(response);
服务器端 我假设您已经为API设置了路由,所以直接进入...
const fs = require('fs');
uploadFile(req, res) {
const requestBody = JSON.parse(req.body);
log.info("Received File Upload request. File " + requestBody.fileName);
// If one doesn't exist, create a folder for the file
fs.existsSync("./SomeFolder/") || fs.mkdirSync("./SomeFolder/");
// Using method.then(otherMethod) with promises.
writeSourceDataToFile (requestBody.fileName,
"./SomeFolder/",
requestBody.fileContent)
.then(v => finalMethod(v, requestBody.fileName, "./SomeFolder/", res))
.catch(err => returnError(res, err) );
}
function writeSourceDataToFile (fileName, path, content) {
return new Promise((resolve, reject) => {
// User fs write stream to stream the file content var to file.
let writeSource = fs.createWriteStream(path + fileName)
.on('end', function () {
log.info("File wrote to disk - End event");
resolve (true);
})
.on('finish', function () {
log.info("File wrote to disk - Finish event");
resolve (true);
})
.on('error', function (err) {
log.info('Error whilst writing file - ' + fileName);
reject (err);
});
writeSource.write(content);
writeSource.end();
});
}
function finalMethod(v, fileName, path, res) {
// Final method just wraps things up and sends some message back to
// client.
log.info(fileName + " File Upload Process Completed.");
res.write("File Upload Process Completed.\n");
res.status(200).end();
}
// Something went wrong, log it and tell the client.
function returnError(res, err) {
log.error(err);
res.status(500).send(err);
}
答案 2 :(得分:0)
您可以使用Multer模块上传文件
const multer = require('multer');
现在设置destinatoin文件夹以保存升级文件
const upload = multer({ dest: './uploads/' });
最后将upload.single()用于单个文件上传,或者将upload.array()用于多个文件上传
app.post('/upload-test',upload.single('myFile'),(request, response) => {
console.log(request.body);
});