简体   繁体   English

使用nodeJS上载时文件已损坏

[英]File is getting corrupted while uploading using nodeJS

This is my server code 这是我的服务器代码

app.post('/tde/api/photo/:widgetId/:choosenFileName',function(req,res){
console.log("In file Upload..");
console.log(req.params.widgetId);
console.log(req.params.choosenFileName);
res.writeHead(200, { 'Content-Type': 'application/binary' });
var filedata = '';
req.setEncoding('binary');
req.on('data', function(chunk){
    filedata+= chunk;
})
req.on('end', function (chunk) {

        var dir = 'uploads/'+req.params.widgetId
        if (!fs.existsSync(dir)){
            fs.mkdirSync(dir);
            console.log("directory created..");
        }


        var fileName = req.params.choosenFileName;
        var widgetId = req.params.widgetId;
            fs.writeFile('uploads/'+widgetId+'/'+fileName, filedata, 'binary', function(err) {
            if (err) {
                return console.error(err);
            }
        })  
    });
res.end("File is uploaded");

}) })

This is my client side code. 这是我的客户端代码。 This is my html file which allows user to choose a file and then upload it to the server location 这是我的html文件,允许用户选择一个文件,然后将其上传到服务器位置

    <div class="col-xs-8">
Upload Image 上传图片
  <span class="warn_msg" ng-if="warningModalWidgetSettingsURLMessage1 != ''"><i class="glyphicon glyphicon-remove-circle"></i> {{warningModalWidgetSettingsURLMessage1}} </span> </div> This is my js file which calls the api of nodejs server $scope.widgetForm.imageConfig = {}; var imageLocationUrl = "http://10.100.10.140/opt/TDE/tde_v2.0-19-01-2016Sanmoy/uploads/" var imageWidgetId = ""; var choosenFileName = ""; $scope.submitFile = function(widgetId){ imageWidgetId = widgetId console.log($scope.fileImage)//this is the file name which I a choosenFileName = $scope.fileImage.name $http({ url: "http://10.100.10.140:9001/tde/api/photo/"+widgetId+"/"+choosenFileName, method: "POST", headers: { 'Content-Type': 'application/binary' }, data: $scope.fileImage, processData: false, contentType: false }).success(function(data, status) { console.log("File Uploaded..") }).error(function(data, status) { console.log("File Upload fail..") }) } 

file is getting uploaded in the server but sometimes it is getting corrupted,can't understand where the problem is. 文件正在服务器中上载,但有时它已损坏,无法理解问题出在哪里。

It seems that you're overwriting 'uploads/report.jpg' every time an upload is done and this may cause corruptions during multiple uploads at the same time: 似乎每次上载完成时都会覆盖“ uploads / report.jpg”,这可能会导致同时进行多个上载期间的损坏:

function(err) {
    var fileName = req.params.choosenFileName;
    var widgetId = req.params.widgetId;
    fs.writeFile('uploads/report.jpg', chunk,  function(err) {
        if (err) {
            return console.error(err);
        }
    })  

What about the commented line: 那注释行呢:

//fs.writeFile('uploads/'+req.params.widgetId+'/sanmoy.jpg', chunk, 

It might be better this way: 这样可能会更好:

fs.writeFile('uploads/'+req.params.widgetId+'/'+fileName', chunk, 

Please note that it would still be possible to upload two or more files with the same 'fileName', so adding some kind of prefix or suffix might be better. 请注意,仍然可以上传两个或多个具有相同“ fileName”的文件,因此添加某种前缀或后缀可能会更好。

UPDATE 1: 更新1:

I just noticed that you're only saving the first chunk. 我只是注意到您只保存了第一块。 The data may fit into one chunk, but it may also consist of multiple chunks. 数据可以容纳一个块,但也可以包含多个块。 Try something like that: 尝试这样的事情:

var filedata = '';
req.setEncoding('binary');

req.on('data', function(chunk){
    filedata+= chunk;
})

req.on('end', function(){
    // create directory etc.
    fs.writeFile('uploads/'+req.params.widgetId+'/'+fileName, filedata, 'binary', function(err){
        if (err) {
            return console.error(err);
    })
})

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

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