使用nodeJS上传文件

时间:2017-05-31 11:24:12

标签: javascript html angularjs node.js

我在使用nodeJS和Angular上传文件时遇到问题。

我找到了解决方案,但它只与Ajax有关,我不知道。是否有可能没有?

使用以下代码我收到此错误:

POST http://localhost:2000/database/sounds 413 (Payload Too Large)

代码:

HTML:

<div class="form-group">
        <label for="upload-input">This needs to be a .WAV file</label>
        <form enctype="multipart/form-data" action="/database/sounds" method="post">
            <input type="file" class="form-control" name="uploads[]" id="upload-input" multiple="multiple">
        </form>
        <button class="btn-primary" ng-click="uploadSound()">UPLOAD</button>
    </div>

使用Javascript:

$scope.uploadSound = function(){
    var x = document.getElementById("upload-input");
    if ('files' in x) {
        if (x.files.length == 0) {
            console.log("Select one or more files.");
        } else {
            var formData = new FormData();
            for (var i = 0; i < x.files.length; i++) {
                var file = x.files[i];
                if(file.type==("audio/wav")){
                    console.log("Importing :");
                    if ('name' in file) {
                        console.log("-name: " + file.name);
                    }
                    if ('size' in file) {
                        console.log("-size: " + file.size + " bytes");
                    }
                    formData.append('uploads[]', file, file.name);
                }else{
                    console.log("Error with: '"+file.name+"': the type '"+file.type+"' is not supported.");
                }  
            }
            $http.post('/database/sounds', formData).then(function(response){
                console.log("Upload :");
                console.log(response.data);
            });

        }
    } 
}

的NodeJS:

//Upload a sound
app.post('/database/sounds', function(req, res){
  var form = new formidable.IncomingForm();

  // specify that we want to allow the user to upload multiple files in a single request
  form.multiples = true;

  // store all uploads in the /uploads directory
  form.uploadDir = path.join(__dirname, '/database/sounds');

  // every time a file has been uploaded successfully,
  // rename it to it's orignal name
  form.on('file', function(field, file) {
    fs.rename(file.path, path.join(form.uploadDir, file.name));
  });

  // log any errors that occur
  form.on('error', function(err) {
    console.log('An error has occured: \n' + err);
  });

  // once all the files have been uploaded, send a response to the client
  form.on('end', function() {
    res.end('success');
  });

  // parse the incoming request containing the form data
  form.parse(req);
});

编辑:

错误变为

POST http://localhost:2000/database/sounds 400 (Bad Request)

4 个答案:

答案 0 :(得分:2)

如果您正在使用bodyParser

app.use(bodyParser.urlencoded({limit: '100mb',extended: true}));
app.use(bodyParser.json({limit: '100mb'}));

这将允许您上传高达100mb的文件

答案 1 :(得分:1)

对于json / urlencoded限制,建议在server / config.json中配置它们,如下所示:

{
“remoting”: {
“json”: {“limit”: “50mb”},
“urlencoded”: {“limit”: “50mb”, “extended”: true}
}

请注意,loopback REST api有自己的带有bodyParser.json / urlencoded中间件的快速路由器。添加全局中间件时,必须在boot()调用之前进行。

var loopback = require('loopback');
var boot = require('loopback-boot');

var app = module.exports = loopback();

//request limit 1gb
app.use(loopback.bodyParser.json({limit: 524288000}));
app.use(loopback.bodyParser.urlencoded({limit: 524288000, extended: true}));

答案 2 :(得分:1)

关于检查数据实际上是否是WAV文件,最好的办法是查看文件的内容并确定是否 WAV文件。

WAVE PCM soundfile format文章详细介绍了格式。

要确保这是一个正确的WAV文件,并且它没有以某种方式破坏,您需要检查那里定义的所有字段是否有意义。但是一个快速的解决方案,可能只是检查内容的前四个字节是字母&#39; RIFF&#39;。它不会防止损坏的文件或恶意内容,但它是我认为开始的好地方。

答案 3 :(得分:0)

我尝试更改发送到url params的对象,如Very Simple AngularJS $http POST Results in '400 (Bad Request)' and 'Invalid HTTP status code 400'中所述:

$http.post({
                method: 'POST',
                url: '/upload',
                data: formData,
                headers: {'Content-Type': 'application/x-www-form-urlencoded'},
                transformRequest: function(obj) {
                    var str = [];
                    for(var p in obj)
                    str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
                    return str.join("&");
                }
            }).success(function(response){
                console.log("Uploaded :");
                console.log(response.data);
            });

但是我收到了错误的请求错误

为什么没有收到数据?此前的console.log显示我的formData中有一个文件。

错误:$ http:badreq 错误的请求配置

Http request configuration url must be a string or a $sce trusted 
object.  Received: {"method":"POST","url":"/upload","data":
{},"headers":{"Content-Type":"application/x-www-form-urlencoded"}}