简体   繁体   English

使用nodeJS上传文件

[英]Upload file with nodeJS

I am having trouble uploading a file with nodeJS and Angular. 我在使用nodeJS和Angular上传文件时遇到问题。

I found solutions but it's only with Ajax which I don't know about. 我找到了解决方案,但它只与Ajax有关,我不知道。 Is it possible to do without? 有可能没有吗?

With the following code I get this error : 使用以下代码我收到此错误:

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

Code: 码:

HTML: 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: 使用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: 的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);
});

EDIT: 编辑:

The error became 错误成了

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

If your are using bodyParser 如果您正在使用bodyParser

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

This will allow you to upload files upto 100mb 这将允许您上传高达100mb的文件

For json/urlencoded limit, it's recommended to configure them in server/config.json as follows: 对于json / urlencoded限制,建议在server / config.json中配置它们,如下所示:

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

Please note loopback REST api has its own express router with bodyParser.json/urlencoded middleware. 请注意,loopback REST api有自己的带有bodyParser.json / urlencoded中间件的快速路由器。 When you add a global middleware, it has to come before the boot() call. 添加全局中间件时,必须在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}));

With regards to checking that the data is actually a WAV file, your best bet is to look at the contents of the file and determine if it looks like a WAV file or not. 关于检查数据实际上是否是WAV文件,最好的办法是查看文件的内容并确定它是否看起来像 WAV文件。

The WAVE PCM soundfile format article goes into the details of the format. WAVE PCM声音文件格式文章详细介绍了该格式。

To be absolutely sure that this is a proper WAV file, and it's not broken in some way, you need to check that all of the fields defined there make sense. 要绝对确定这是一个正确的WAV文件,并且它没有以某种方式破坏,您需要检查那里定义的所有字段是否有意义。 But a quick solution, might be to just check that the first four bytes of the content are the letters 'RIFF'. 但是快速解决方案可能只是检查内容的前四个字节是字母“RIFF”。 It won't guard against corrupted files or malicious content, but it's a good place to start I think. 它不会防止损坏的文件或恶意内容,但我认为这是一个好的开始。

I tried to change the object sent to url params as said in Very Simple AngularJS $http POST Results in '400 (Bad Request)' and 'Invalid HTTP status code 400' : 我尝试更改发送到url params的对象,如在'400(错误请求)'和'无效HTTP状态代码400'中的非常简单AngularJS $ http POST结果中所述:

$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);
            });

But I get a bad request error 但我得到一个错误的请求错误

Why is there no data received ? 为什么没有收到数据? The console.log before this shows I have one file in my formData. 之前的console.log显示我的formData中有一个文件。

Error: $http:badreq Bad Request Configuration 错误:$ 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"}}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM