1 回答
TA贡献1869条经验 获得超4个赞
我创建了一个单独的插件,用于将文件 [本机级别] 保存到 Cordova 中的 Android 和 IOS 设备中。我觉得现有的文件编写器插件有问题
爪哇
private Boolean saveImage(final CallbackContext callbackContext, final String bs64String) {
cordova.getThreadPool().execute(new SocialSharingRunnable(callbackContext) {
public void run() {
//Directory and File
try {
String dirName = webView.getContext().getExternalFilesDir(null) + "/";
File dir = new File(dirName);
File file = new File(dirName, cordova.getActivity().getApplicationContext().getString(R.string.filename)+".png");
Log.d("SaveFile", "Save Image");
Log.d("SaveFile", "dirName "+dirName);
//Avoid overwriting a file
/* if (!overwrite && file.exists()) {
callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, "File already exists!"));
}*/
//Decode Base64 back to Binary format
byte[] decodedBytes = Base64.decode(bs64String.getBytes(), Base64.DEFAULT);
//Save Binary file to phone
file.createNewFile();
FileOutputStream fOut = new FileOutputStream(file);
fOut.write(decodedBytes);
fOut.close();
callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, "Saved successfully!"));
} catch (FileNotFoundException e) {
callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, "File not Found!"));
} catch (IOException e) {
callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, e.getMessage()));
}
}
});
return true;
}
IOS
- (void)saveImage:(CDVInvokedUrlCommand*)command {
CDVPluginResult *pluginResult;
@try
{
NSLog(@"========== saveImage ========");
NSString* strBase64Img = [command.arguments objectAtIndex:0];
NSLog(@"strBase64Img %@",strBase64Img);
NSData *imageData = [Sharing dataFromBase64String:strBase64Img];
UIImage *image = [UIImage imageWithData:imageData];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSLog(@"paths %@",paths);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSLog(@"documentsDirectory %@",documentsDirectory);
NSString *getImagePath = [documentsDirectory stringByAppendingPathComponent:@"ImageName.png"];
[UIImagePNGRepresentation(image) writeToFile:getImagePath atomically:YES];
NSString *savedImage = @"Successfully saved";
pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:savedImage];
[self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
}
@catch(id anException) {
NSString *failImg = @"Failed to Save";
pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:failImg];
[self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
}
}
脚本语言
cordova.exec(onSaveSuccess, onSaveError, "Sharing", "saveImage", [base64Canvas]);
添加回答
举报