Angularjs上传文件至Koa并转发至Java

前端使用Angularjs上传至Koa,Koa再将文件转发至Java后台。

使用说明

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;ivar 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;ivar 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

你可能感兴趣的:(Angularjs上传文件至Koa并转发至Java)