我有这样的代码,可以使用Node.js、Express和Multer上传单个文件:
var express = require("express");
var app = express();
var fs = require("fs");
var multer = require('multer');
var upload = multer({ dest: 'uploads/' });
// Process upload file
app.post('/file_upload', upload.single('single-file'), function(request, response) {
var fileName = request.file.originalname;
var filePath = request.file.path;
var file = __dirname + "/uploads/" + fileName;
fs.readFile(filePath, function(err, data) {
fs.writeFile(file, data, function(err) {
if (err) {
console.log(err);
} else {
responseData = {
'message' : 'File uploaded successfully',
'fileName' : fileName
};
}
response.end(JSON.stringify(responseData));
})
});
});
以下是HTML文件:
<!DOCTYPE html>
<html>
<head>
<title>File Uploading Form</title>
</head>
<body>
<h3>File Upload:</h3>
Select a file to upload: <br />
<form action="http://localhost:8081/file_upload" method="POST"
enctype="multipart/form-data">
<input type="file" name="single-file" size="50" />
<br />
<input type="submit" value="Upload File" />
</form>
</body>
</html>
运行代码后,我成功上传了文件。 但问题是,每次我都会在我的“uploads”文件夹中得到两个上传的文件。一个文件是原始名称,另一个文件是类似于2787ab2db292d90bd2da83a6a6ce1700这样的奇怪名称。
这正常吗?我该如何在上传时摆脱另一个文件?
enctype="multipart/form-data"
。 - AdityaParab