使用ajax和node.js上传文件而不使用express

时间:2014-03-20 04:30:44

标签: javascript ajax node.js multipartform-data formidable

你好我们正在尝试用ajax和节点发送文件,但是我没有找到告诉我如何做的信息!!,我现在建立了一个脚本,但我可以关注更多

var server=http.createServer(function(req, res){
    if(req.url==='/upload'){
        if(req.method==='OPTIONS'){//OPTIONS is the method that show in the server when i send files
            req.on('data', function(a){
                console.log(a);//i dont know what are?? after to here!!
            });
        }
    }
});

我听过一些模块,比如强大的,multipartbusboy但是我无法运行它

由于

我可以用FORMIDABLE解决它:)看下一个代码:

var server=http.createServer(function(req, res){
    if(req.url==='/upload'){
        var headers = {};
              // IE8 does not allow domains to be specified, just the *
              // headers["Access-Control-Allow-Origin"] = req.headers.origin;
              headers["Access-Control-Allow-Origin"] = "*";
              headers["Access-Control-Allow-Methods"] = "POST, GET, PUT, DELETE, OPTIONS";
              headers["Access-Control-Allow-Credentials"] = false;
              headers["Access-Control-Max-Age"] = '86400'; // 24 hours
              headers["Access-Control-Allow-Headers"] = "X-Requested-With, X-HTTP-Method-Override, Content-Type, Accept";
        if(req.method==='OPTIONS'){
              res.writeHead(200, headers);
              res.end();
        }else if(req.method==='POST'){
            var form = new formidable.IncomingForm(),
                files = [],
                fields = [];
            form.uploadDir = '/home/sonick7/';//direccion donde va a ser gusradado

            form.on('field', function(field, value) {
                fields.push([field, value]);
              })
              .on('file', function(field, file) {
                console.log(file.name, file.size, file.type, file.path)
                files.push([field, file]);
              })
              .on('end', function() {
                console.log('Upload terminado ');
                res.writeHead(200, headers);
                res.end();
              });
            form.parse(req);//no se que hace eso y para que sirve el modulo util?
        }
    }
});

2 个答案:

答案 0 :(得分:1)

更新并解决

let server=http.createServer((req, res)=>{
    if(req.url==='/upload'){
        let headers = {}
              // IE8 does not allow domains to be specified, just the *
            headers={
                'Access-Control-Allow-Origin':'*',
                'Access-Control-Allow-Methods':'POST, GET, PUT, DELETE, OPTIONS',
                'Access-Control-Allow-Credentials':false,
                'Access-Control-Max-Age':'86400', // 24 hours
                'Access-Control-Allow-Headers':'X-Requested-With, X-HTTP-Method-Override, Content-Type, Accept'
              }
        if(req.method==='OPTIONS'){
              res.writeHead(200, headers)
              res.end()
        }else if(req.method==='POST'){
            let form=new formidable.IncomingForm(),
                files=[],
                fields=[]
            form.uploadDir='/home/sonick7/'

            form.on('field', (field, value)=>{
                fields.push([field, value])
            })
            .on('file', (field, file)=>{
                files.push([field, file])
            })
            .on('end', ()=>{
                console.log(files, fields, 'FT here awefwa', __filename)
                console.log('Upload terminado ')
                res.writeHead(200, headers)
                res.end()
            })
            form.parse(req)
        }
    }
})

答案 1 :(得分:0)

如果您收到客户端OPTIONS的请求,则可能意味着客户端首先发送CORS请求。我不确定您使用的是哪个客户端库,AFAKI AngularJS将在每个Ajax请求中发送CROS请求。

所以你需要在服务器端做什么来处理这个OPTIONS请求,告诉客户端这是一个有效的CROS请求,然后客户端应该发送文件上传请求(也许POST)。

以下代码是我在项目中使用{em} DEV 环境中使用express模块处理CORS请求的原因,这意味着它允许来自任何来源的请求。在生产环境中,您需要检查原始标题并接受您信任的标题。

    app.configure(function () {
        app.use(function (req, res, next) {
            var oneof = false;
            if (req.headers.origin) {
                res.header('Access-Control-Allow-Origin', '*');
                oneof = true;
            }
            if (req.headers['access-control-request-method']) {
                res.header('Access-Control-Allow-Methods', 'OPTIONS, HEAD, GET, POST, PUT, DELETE');
                oneof = true;
            }
            if (req.headers['access-control-request-headers']) {
                res.header('Access-Control-Allow-Headers', 'Content-Type, Content-Range, Content-Disposition, Authentication');
                oneof = true;
            }
            if (oneof) {
                res.header('Pragma', 'no-cache');
                res.header('Cache-Control', 'no-store, no-cache, must-revalidate');
                res.header('Content-Disposition', 'inline; filename="files.json"');
            }
            if (oneof && req.method == 'OPTIONS') {
                res.send(200);
            }
            else {
                next();
            }
        });
    });