最近在用uniapp开发,做选文件上传的需求时遇到这样一个问题,选完文件获取到路径后,发现插件获取的文件路径,无法用于上传,不是报文件无法读、就是找不到文件。
开始用了download、saveFile等方法都无法解决,官方文档也贫瘠,简直令人头秃。
老夫呕心沥血才得以解决,记录下!
解决方法如下
一、利用插件获取到的文件路径为:
"url": "file:///private/var/mobile/Containers/Data/Application/462656A1-10D4-4BC0-AD6C-7A5BABFE0E64/tmp/com.vv.work-Inbox/%E4%B8%AD%E5%8D%8E%E4%BA%BA%E6%B0%91%E5%85%B1%E5%92%8C%E5%9B%BD%E5%8A%B3%E5%8A%A8%E6%B3%95.pdf"
此时文件在temp目录下且为private,无法直接拿到file用于上传。
二、此时需要将此文件,copy到项目沙盒目录下,拷贝后沙盒目录下的文件路径才能用于上传。
1、获取项目沙盒路径
var copyPath = plus.io.convertLocalFileSystemURL("_doc/vv-work");
var copyPathName = copyPath + "/" + result.lastName;
(result.lastName是文件后缀名)
2、如果文件名有包含中文的,需要将url进行反编码
var urlLocal = plus.io.convertLocalFileSystemURL(url);
decodeURIComponent(urlLocal)
3、接下来就是拷贝文件到项目沙盒目录了
const p = utils.copyPathToSandboxPath(copyPath, copyPathName, decodeURIComponent(urlLocal));
p.then(function (res) {
// ***file:// 不加的话 文件名含中文的 找不到文件
let filePath = "file://" + copyPathName;
console.log("~~~~~~copye finish -> filePath: ",filePath);
// filePath 就是我们要的结果
that.chooseFileResult({
path: filePath
});
}, function (e) {
console.log("~~~~~~ e: ",e);
});
filePath最后的结果:
file:///var/mobile/Containers/Data/Application/462656A1-10D4-4BC0-AD6C-7A5BABFE0E64/Documents/Pandora/apps/A5A9973252A36C7ACF7F799B7381EB04/doc/vv-work/中华人民共和国劳动法.pdf
4、附上copyPathToSandboxPath方法
// iOS文件拷贝至沙盒目录下
copyPathToSandboxPath(copyPath, copyPathName, filePath) {
return new Promise((resolve, reject) => {
console.log("copy -> copyPath:"+copyPath);
console.log("copy -> copyPathName:"+copyPathName);
console.log("copy -> filePath:"+filePath);
filePath = filePath.replace("file://", "");
var NSFileManager = plus.ios.importClass("NSFileManager");
var fileManager = NSFileManager.defaultManager();
var isFileExist_Path = plus.ios.invoke(fileManager, "fileExistsAtPath:", copyPath);
console.log("isFileExist_Path:" + isFileExist_Path);
if (isFileExist_Path == false) {
var isCreateDirectory = plus.ios.invoke(fileManager, "createDirectoryAtPath:withIntermediateDirectories:attributes:error:", copyPath, true, null, null);
console.log("isCreateDirectory:" + isCreateDirectory);
}
var isFileExist_PathName = plus.ios.invoke(fileManager, "fileExistsAtPath:", copyPathName);
console.log("isFileExist_PathName:" + isFileExist_PathName);
if (isFileExist_PathName == true) {
// 如果存在 删除
var isRemove = plus.ios.invoke(fileManager, "removeItemAtPath:error:", copyPathName, null);
console.log("isRemove:" + isRemove);
}
// plus.ios.invoke(fileManager, "copyItemAtPath:toPath:error:", filePath, copyPathName, null);
var isCopy = plus.ios.invoke(fileManager, "copyItemAtPath:toPath:error:", filePath, copyPathName, null);
if (isCopy) {
console.log("FFFFFF isCopy true :" + copyPathName);
resolve("success")
} else {
console.log("FFFFFF copyItem failed")
reject("failed")
}
})