使用nodeJS上传时文件已损坏

时间:2016-02-03 11:09:37

标签: javascript html angularjs node.js

这是我的服务器代码

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");

})

这是我的客户端代码。 这是我的html文件,允许用户选择一个文件,然后将其上传到服务器位置

    <div class="col-xs-8">
                                                                                                 上传图片                                             
                                        <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..")
        })
    }

文件正在上传到服务器中,但有时会被破坏,无法理解问题所在。

1 个答案:

答案 0 :(得分:1)

每次上传完成后,您似乎都会覆盖'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);
        }
    })  

注释行怎么样:

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

这样可能会更好:

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

请注意,仍然可以上传两个或多个具有相同'fileName'的文件,因此添加某种前缀或后缀可能会更好。

更新1:

我刚注意到你只保存了第一块。数据可能适合一个块,但它也可能包含多个块。尝试类似的东西:

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