我的应用程序中有此设置-
Angular 7->节点服务器-> springboot API。
Angular应用上有一些页面将json发送到API。还有其他一些需要发送上载的图像文件。我无法将上传的图像发送到节点服务器和API。我的代码段如下。在app.js中,req.body和req.file分别显示为空和未定义。我在网站上浏览了类似的问题,但无法使我的代码正常工作。我要去哪里错了?非常感谢您的帮助。
console.log(req.body); // form fields
console.log(req.file); // form files
module.component.html
<input type="file" name="file-to-upload" (change)="onFileChanged($event.target.files)">
<div style="margin-top: 20px;">
<button mat-raised-button type="button (click)="onSubmitCreateTemplate()">
Submit
</button>
<button mat-raised-button color="primary" (click)="onCancel()">Cancel</button>
</div>
module.component.ts
export class ModuleComponent implements OnInit {
...
onFileChanged(files: FileList) {
this.fileName = files.item(0);
}
public onSubmitCreateTemplate() {
this.moduleService.createTemplate(
this.receiptForm.value['merchantID'] === null ? '' : this.receiptForm.value['merchantID'],
"some string",
'Draft',
this.fileName
).subscribe(
...
);
}
moduleService.ts
export class ModuleService {
geHeaders() {
const httpheaders = {
headers: new HttpHeaders({
'Content-Type': 'multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW'
})
};
return httpheaders;
}
createTemplate(merchantId: string, template: string, templateStatus: string, logoImageFile: File) {
let headerInfo = this.geHeaders();
const url = `${this.receiptTemplateUrl}`;
let formData = new FormData();
formData.append('file-to-upload', logoImageFile, logoImageFile.name);
return this.http.post(url, formData, headerInfo);
}
}
proxy-server.js
const express = require('express');
const bodyParser = require('body-parser');
const http = require('http');
var multer = require("multer")
var upload = multer();
const app = express();
const httpServer = http.createServer(app);
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
// for parsing multipart/form-data
app.use(upload.array());
app.use(express.static('public'));
const appRoute = require('./server/routes/app');
app.use('/api', appRoute);
const port = process.env.PORT || 3000;
if (process.env.NODE_ENV === 'development') {
httpServer.listen(port);
} else {
// for integration and production
httpServer.listen(3000);
}
app.js
我不想将文件保存在磁盘上,而是必须将其发送到后端api。我试图保存在磁盘上,只是为了查看文件是否已保存。不幸的是,文件没有被保存。
const express = require('express');
const router = express.Router();
const request = require('request');
const { logger } = require('./../helpers/logger');
const mposLogger = logger('mppp');
var multer = require("multer")
var storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, 'uploads')
},
filename: (req, file, cb) => {
cb(null, file.fieldname + '-' + Date.now())
}
});
var upload = multer({storage: storage});
router.route('/:serviceName/admin/receipt').post(upload.single("file-to-upload"), function(req, res, next){
console.log(req.body); // form fields
console.log(req.file); // form files
});
router.all('/:serviceName/*', (req, res) => {
...
});
module.exports = router;
@RestController
@RequestMapping("/admin")
public class TemplateController extends AbstractController {
...
@RequestMapping(path="/receipt",method= RequestMethod.POST)
public IResponse createTemplate(@RequestHeader Map<String,String> header,
/*@Valid AddTemplateRequest request,*/
@RequestParam("file") MultipartFile imageFile) throws GenericException {
...
}
This is the form-data sent from the browser.
在节点服务器端,console.log(req.file)打印'undefined'。