如何使用Koa将文件上传至Java后台,前端使用Angularjs上传至Koa
使用说明
springmvc代码
@PostMapping("upload")
public Result upload(@RequestParam("files") MultipartFile[] files) throws FileNotFoundException {
if (null != files) {
try {
for(MultipartFile multipartFile : files){
multipartFile.transferTo(new File("/home/lake/github/file/" + multipartFile.getOriginalFilename()));
}
return new ActResult("success");
} catch (IOException e) {
e.printStackTrace();
}
}
return new ActResult("error");
}
Koa代码
const router = require("koa-router")();
const request = require('request-promise');
const fs = require('fs');
router.post('/upload',koaBody({multipart:true}),function *(next) {
var $self = this;
var file = this.request.body.files.files;
var files = [];
if(file instanceof Array){
for(var i =0;i<file.length;i++){
var f = file[i];
var oo = {
value:fs.createReadStream(f.path),options: {
filename: f.name,contentType: f.mimeType
}
};
files.push(oo);
}
}else{
var oo = {
value:fs.createReadStream(file.path),options: {
filename: file.name,contentType: file.mimeType
}
};
files.push(oo);
}
var options = {
url: 'http://localhost:8888/wopi/upload',method: 'POST',formData: {
files: files
}
};
yield (request(options).then(function (body) {
$self.body = body;
}));
});
Angularjs代码
$scope.upload = function () {
var fd = new FormData();
var file = document.getElementById('abc').files;
for(var i =0;i<file.length;i++){
var f= file[i];
fd.append('files',f);
}
$http({
method: 'POST',url: '/upload',headers: {
'Content-Type': undefined
},data: fd,transformRequest: angular.identity
},function (data) {
console.info(data);
});
}
流程
Angularjs -> Koa ->Java