使用 AngularJS 和 ng 文件上传保持文件重命名的原始格式
Keeping original format on file rename using AngularJS and ng File Upload
我正在使用 ng-file-upload 在网络应用程序中上传图片。
上传过程运行良好,但是当我尝试使用 momentJS 为每个文件指定一个唯一的名称时,它不会自动保持格式并在没有文件扩展名的情况下保存它。
例如image.jpg会变成12-07-2016-23-36-44.
我设法使用以下代码解决了这个问题,但它会将所有图像保存为 JPG,即使它们不是(PNG、GIF...)
$scope.uniquelogo = moment().format('DD-MM-YYYY-HH-mm-ss') + '.jpg';
Upload.upload({
url: 'upload.php',
data: {
file: file,
name: Upload.rename(file, $scope.uniquelogo)
}
我怎样才能使用 Upload.rename() 并仍然保留原始文件格式?
您可以从原始文件名中检索扩展名并使用它代替 .jpg
。
function getFileExtension(filename) {
return filename
.split('.') // Split the string on every period
.slice(-1)[0]; // Get the last item from the split
}
$scope.uniquelogo = moment().format('DD-MM-YYYY-HH-mm-ss');
Upload.upload({
url: 'upload.php',
data: {
file: file,
name: Upload.rename(file, $scope.uniquelogo + getFileExtension(file.name))
}
...
您可以访问 属性 type 来获取扩展名,但是 例如:
- 图片/(jpeg|png)
- video/mp4
因此您可以使用 string
方法 String.prototype.substring()
+ String.prototype.lastIndexOf()
只获取您想要的部分:
name: Upload.rename(file, $scope.uniquelogo + file.name.substring(file.type.lastIndexOf('/'), file.name.length).replace('/', '.'));
注意:我用replace的方法将"/"
替换为"."
,不过你也可以手工完成(只要把$scope.uniquelogo + '.' + file.name.substring(file.type.lastIndexOf('/') + 1, file.name.length)
希望对您有所帮助!
我正在使用 ng-file-upload 在网络应用程序中上传图片。
上传过程运行良好,但是当我尝试使用 momentJS 为每个文件指定一个唯一的名称时,它不会自动保持格式并在没有文件扩展名的情况下保存它。
例如image.jpg会变成12-07-2016-23-36-44.
我设法使用以下代码解决了这个问题,但它会将所有图像保存为 JPG,即使它们不是(PNG、GIF...)
$scope.uniquelogo = moment().format('DD-MM-YYYY-HH-mm-ss') + '.jpg';
Upload.upload({
url: 'upload.php',
data: {
file: file,
name: Upload.rename(file, $scope.uniquelogo)
}
我怎样才能使用 Upload.rename() 并仍然保留原始文件格式?
您可以从原始文件名中检索扩展名并使用它代替 .jpg
。
function getFileExtension(filename) {
return filename
.split('.') // Split the string on every period
.slice(-1)[0]; // Get the last item from the split
}
$scope.uniquelogo = moment().format('DD-MM-YYYY-HH-mm-ss');
Upload.upload({
url: 'upload.php',
data: {
file: file,
name: Upload.rename(file, $scope.uniquelogo + getFileExtension(file.name))
}
...
您可以访问 属性 type 来获取扩展名,但是 例如:
- 图片/(jpeg|png)
- video/mp4
因此您可以使用 string
方法 String.prototype.substring()
+ String.prototype.lastIndexOf()
只获取您想要的部分:
name: Upload.rename(file, $scope.uniquelogo + file.name.substring(file.type.lastIndexOf('/'), file.name.length).replace('/', '.'));
注意:我用replace的方法将"/"
替换为"."
,不过你也可以手工完成(只要把$scope.uniquelogo + '.' + file.name.substring(file.type.lastIndexOf('/') + 1, file.name.length)
希望对您有所帮助!