重命名文件通过Angularjs上传 [英] Renamed a file uploaded via Angularjs

查看:408
本文介绍了重命名文件通过Angularjs上传的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

概括地说,我需要重命名通过角和节点上传的文件,并做出新的名字提供给双方的背部和前端(我认为)。什么是这样做的最佳做法?

我使用的是文件上传插件( https://github.com/danialfarid/angular-在Angularjs应用程序文件上传)。上传命中通过处理的NodeJS的路线,上传文件,然后,成功,角保存到一个用户占的文件名。然而,如果两个人上传同一名称的文件会有冲突,所以我需要(可能通过添加日期和时间)到重命名每个文件

I am using a file upload plugin (https://github.com/danialfarid/angular-file-upload) in an Angularjs app. The upload hits a route handled by Nodejs, uploads the file then, on success, angular saves the file name into a users account. However, if two people upload a file of the same name there will be a conflict so I need to rename each file (perhaps by adding a date and time).

我的code的工作原理如下:

My code works as follows:


  1. 角处理上载,创下该节点可以使用的路由。

  2. 节点将文件移动到的地方。

  3. 在成功的,棱角分明的保存文件名到用户的帐户。

看来我不能前上传重命名文件。如果我重新命名通过节点的文件时,它已被移动到位后,我碰到需要获得新的名称回角保存到数据库中的问题。不知道的接近这一过程的最好方式。

It appears I cannot rename the file prior to uploading. If I rename the file via node after it has been moved into place I run into the issue of needing to get that new name back to angular for saving into the database. Not sure of the best way to approach this process.

下面是我当前的文件上传code(工作得很好,只是不重命名文件):

Here is my current file upload code (works fine, just doesn't rename the file):

在角...

   $scope.onFileSelect = function ($file) {
        var photo = $file[0];
        $scope.upload = $upload.upload({
            url: '/upload/userphoto',
            headers: {'Content-Type': photo.type},
            file: photo,
            method: 'POST'
        }).progress(function (evt) {
            //removed for brevity
        }).success(function (data, status, headers, config) {
            User.currentUser.user_profile_image = photo.name;
            User.updateUser();
        }).error(function (err) { 
            //removed for brevity 
        });
    };

该职位的路线, /上传/ userphoto 在节点与匹配:

exports.uploadProfilePhoto = function(req, res) {
    var callbacks = {};

    callbacks.uploadSuccess = function(){
        res.json('success');
    };

    callbacks.uploadFailure = function(err){
        //removed for brevity
    };

    user.handleUserImageUpload(req.files, callbacks);
};

其中规定了一些回调,然后点击 handleUserImageUpload()是:

this.handleUserImageUpload = function(params, callbacks) {
    fs.readFile(params.file.path, function(err, data){
        if(err){
            callbacks.uploadFailure(err);
        }
        var newPath = path.resolve("./public/fileupload/userphotos/" + params.file.filename);
        fs.writeFile(newPath, data, function(err) {
            if(err){
                callbacks.uploadFailure(err);
            }
            callbacks.uploadSuccess();
        });
    });
};

其中,假设成功,把我们带回到上面的角code的第一位成功的处理程序。我知道我可以用 handleUserImageUpload()方法重命名文件fs.rename()一样(只是一个硬codeD播放的范例......我真的考虑到文件类型和现有的名称加上添加一个随机字符串或帐户标识符):

Which, assuming success, takes us back to the success handler of the first bit of Angular code above. I know I can rename the file in the handleUserImageUpload() method with fs.rename() like (just a hard coded example... I would actually take into account the file type and existing name plus add a random string or account identifier):

var renamedPath = path.resolve("./public/fileupload/userphotos/" + "abc123.jpg");
fs.rename(newPath, renamedPath);

但后来我没有可用的新名字,当我去保存文件信息到用户的帐户。我想我可以通过它回到了成功的回调?是最好的办法还是我失去了一些东西?

But then I don't have that new name available when I go to save the file info into the user's account. I guess I could pass it back in the success callback? Is that the best way or am I missing something?

推荐答案

解决方案竟然是什么,我怀疑...在回调传递值。所以我添加以下内容 handleUserImageUpload() ...

The solution turned out to be what I suspected... pass the value in the callback. So I added the following to handleUserImageUpload()...

// grab the extension
var fileExtension = '.' + params.file.filename.split('.').pop();

// rename the file with a sufficiently random value and add the file extension back
var renamedFile =  Math.random().toString(36).substring(7) + new Date().getTime() + fileExtension;

//set up the new path for use in fs.rename()
var renamedPath = path.resolve("./public/fileupload/userphotos/" + renamedFile);

// Make it so
fs.rename(newPath, renamedPath);

// pass the new name to the callback
callbacks.uploadSuccess(renamedFile);

在创建回调函数, uploadProfilePhoto(),我需要做一个重要的变化,掉期 JSON 发送(否则我会得到引号添加到值)

In the function that created the callbacks, uploadProfilePhoto(), I needed to make one important change, swap json with send (otherwise I would get quotation marks added to the value)

//res.json('success');
res.send(renamedFile);

然后,我可以访问这个名字作为我的角成功处理程序的数据值。

这篇关于重命名文件通过Angularjs上传的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆