I have a remote directory with several subdirectories and files in them on Dropbox.
remote side:
-Mobile Profiles *(root)*
-- Custom Profiles
--- Profile1
--- Profile2
--- Profile3
Uploading the files and directories / and subdirectories with files is not a problem. I am having a brain fart when it comes to getting the subdirectories and their contents from dropbox to the device.
put
-(void)backupCustomProfiles {
for ( NSString *file in [[NSFileManager defaultManager] contentsOfDirectoryAtPath:MP_CUSTOM error:&error] ) {
[self.restClient uploadFile:file toPath:#"/Mobile Profiles/Custom Profiles/" fromPath:EasyStrings(MP_CUSTOM,file)];
}
}
get
-(void)restoreCustomProfiles {
for ( ) {
/* ? */
}
}
I am not sure how to iterate through the subdirectories on the remote side.
First load the directory metadata, then load the files that it references.
To limit the number of parallel fetches, use a NSOperationQueue for all of the loadMetadata and loadFile calls to limit the number of parallel fetches. And to avoid redundant file downloads, remember the downloaded metadata in a plist.
- (void) restoreCustomProfiles
{
[self.client loadMetadata:#"/Mobile Profiles/Custom Profiles" withHash:hash];
}
- (void) restClient:(DBRestClient*)client loadedMetadata:(DBMetadata*)metadata
{
for (DBMetadata* child in metadata.contents) {
NSString *path = [child.path lowercaseString];
if (child.isDirectory) {
[client loadMetadata:child.path withHash:hash];
} else {
[client loadFile:pathToDownload intoPath:[
self.directory stringByAppendingString:path]];
}
}
}
- (void) restClient:(DBRestClient*)client loadedFile:(NSString*)destPath
{
// successfully downloaded a file to destPath
}
Related
Recently i'm using cocos 2d-x ver-3.17.
I complied resource to jsc then make a server to upload it like update-server, control version i think.
Now when i build the app in IOS which will connect to update-server then download the file jsc. Unfortunately, when the app trying to save the file down it falling to the error " don't have permission to save the file". What should i do to provide them permission to solve it.
Fail to create directory :
"/var/mobile/Containers/Data/Application/C9BA91B9-AEF6-4FF8-B5F3-061AF15441A5/Documents_temp/":
You don’t have permission to save the file “Documents_temp” in the
folder “C9BA91B9-AEF6-4FF8-B5F3-061AF15441A5”.
bool FileUtilsApple::createDirectory(const std::string& path)
{
CCASSERT(!path.empty(), "Invalid path");
if (isDirectoryExist(path))
return true;
NSError* error;
bool result = [s_fileManager createDirectoryAtPath:[NSString stringWithUTF8String:path.c_str()] withIntermediateDirectories:YES attributes:nil error:&error];
if(!result && error != nil)
{
CCLOGERROR("Fail to create directory \"%s\": %s", path.c_str(), [error.localizedDescription UTF8String]);
}
return result;
}
How can i get permission to save the files ?
solved : https://forum.cocos.com/t/topic/47298/3
Self-reliance, find out the problem, you need to define the file directory
find your initAssetManager :
var storagePath = (jsb.fileUtils ? jsb.fileUtils.getWritablePath() : "./")+"temp/";
In this way, I download a image successfully:
GTLServiceDrive *drive = ...;
GTLDriveFile *file = ...;
NSString *url = [NSString stringWithFormat:#"https://www.googleapis.com/drive/v3/files/%#?alt=media",file.identifier];
GTMSessionFetcher *fetcher = [drive.fetcherService fetcherWithURLString:url];
[fetcher beginFetchWithCompletionHandler:^(NSData *data, NSError *error) {
if (error == nil) {
NSLog(#"Retrieved file content");
// Do something with data
} else {
NSLog(#"An error occurred: %#", error);
}
}];
the document of google drive sdk tell me to download a pdf or google docs should use another url:
NSString *url = [NSString stringWithFormat:#"https://www.googleapis.com/drive/v3/files/%#/export?alt=media&mimeType=application/pdf",file.identifier];
but I failed, error is this:
{
"error": {
"errors": [
{
"domain": "global",
"reason": "badRequest",
"message": "Bad Request"
}
],
"code": 400,
"message": "Bad Request"
}
}
In downloading file make sure your app must be authorized with a scope that allows reading of file content. For example, an app using the drive.readonly.metadata scope would not be authorized to download the file contents. Users with edit permission may restrict downloading by read-only users by setting the viewersCanCopyContent field to true.
There is another way to download a file by using the partial download. It involves downloading only a specified portion of a file. You can specify the portion of the file you want to dowload by using a byte range with the Range header.
This SO question is using partial download. I think it can help you.
This code demonstrate how to download a Google Document in PDF format.
String fileId = "1ZdR3L3qP4Bkq8noWLJHSr_iBau0DNT4Kli4SxNc2YEo";
OutputStream outputStream = new ByteArrayOutputStream();
driveService.files().export(fileId, "application/pdf")
.executeMediaAndDownloadTo(outputStream);
I just started to use apache commons vfs 2.0. I was trying to get file list of folder in c:\ but got error with c:\document and setting. Here is the code:
FileSystemManager fsm = VFS.getManager();
FileObject fo=fsm.resolveFile("c:\\");
FileObject[] fos=fo.getChildren();
for(FileObject f:fos){
FileType ft=f.getType();
if(f.getType().equals(FileType.FOLDER)){
for( FileObject fc:f.getChildren()){
System.out.println(fc.getName().getPath());
}
}
}
Error:
org.apache.commons.vfs2.FileNotFolderException: Could not list the contents of "file:///c:/Documents and Settings" because it is not a folder.
at org.apache.commons.vfs2.provider.AbstractFileObject.getChildren(AbstractFileObject.java:693)
at mypack.gui.FileExplorer.<init>(FileExplorer.java:31)
at mypack.gui.FileExplorer.main(FileExplorer.java:42)
You have to use proper protocol to connect via VFS Try this:
FileSystemManager fsm = VFS.getManager();
FileObject fo=fsm.resolveFile("file:///c:/");
FileObject[] fos=fo.getChildren();
for(FileObject f:fos){
FileType ft=f.getType();
if(f.getType().equals(FileType.FOLDER)){
for( FileObject fc:f.getChildren()){
System.out.println(fc.getName().getPath());
}
}
}
As all Db files of Calls, SMS, Emails and Calender etc are present in,
SMS: /Var/Mobile/Library/SMS
Contacts /User/Library/AddressBook
Mail: /Var/Mobile/Library/Mail
Calendar: /Var/Mobile/Library/Calendar
Call History: /Var/Mobile/Library/CallHistory
Notes: /Var/Mobile/Library/Notes
Safari: /Var/Mobile/Library/Safari
how to create backup files of above all programmatically.
You Can try this if you want to backup that database to your device. apple may not allow you to access the db files of call lists.
if (![[NSFileManager defaultManager] fileExistsAtPath:#"YOUR DB FILE PATH"])
{
if ([[NSFileManager defaultManager] copyItemAtPath:"YOUR DB FILE PATH" toPath:#"PATH WHERE YOU WANT TO BACKUP" error:nil])
{
NSLog(#"Backuped");
}
else
{
NSLog(#"Error in backuping the database");
}
}
I'm uploading a pdf file from an iOS application to a Rails application.
The file is uploaded, but its content type gets corrupted.
Here is the relevant part of the iOS code to upload the file (using AFNetworking library):
NSURL *url = [NSURL URLWithString:kWebserviceHost];
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url];
// httpClient.parameterEncoding = AFFormURLParameterEncoding; // Experimented with different values, no effect
NSData *documentData = [NSData dataWithContentsOfURL:self.documentURL];
if (! documentData) {
NSLog(#"Trying to upload nil document: sorry! - %#", self.documentData);
return;
}
NSMutableURLRequest *request = [httpClient multipartFormRequestWithMethod:#"PUT" // #"POST"
path:#"new_upload"
parameters:#{ #"fooKey" : fooString, #"barKey" : barString }
constructingBodyWithBlock: ^(id <AFMultipartFormData>formData) {
[formData appendPartWithFileData:documentData name:#"document" fileName:#"upload.pfd" mimeType:#"application/pdf"];
}];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[operation setUploadProgressBlock:^(NSInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) {
NSLog(#"Sent %lld of %lld bytes", totalBytesWritten, totalBytesExpectedToWrite);
progressBlock(totalBytesWritten / totalBytesExpectedToWrite);
}];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
uploadSuccessBlock();
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Sorry, could not upload document - %#", error);
failureBlock(error);
}];
[operation start];
Let's go to the other side, a Rails 3.2.3 server.
I'm using the gem PaperClip (version 3.1.4). Here is the definition of the paperclip attachment in my model class:
paperclip_storage = (Rails.env.production?) ? {
:storage => :s3,
:s3_credentials => "#{Rails.root}/config/s3.yml",
:path => ':attachment/:id/:style.:extension',
:bucket => 'mybucketname' #,
# :s3_headers => { "Content-Type" => "video/mp4" }
}
: { :headers => { "Content-Type" => "application/pdf" }
}
has_attached_file :document, paperclip_storage.merge( :use_timestamp => false,
:url => "/assets/:id/:basename.:extension",
:path => ":rails_root/public/assets/:id/:basename.:extension",
:processors => nil # Maybe the processing of the file mess things up?
)
I also tried to skip the post process (even though the documentation says none should be applied because no style is defined).
before_post_process :skip_post_process
def skip_post_process
return false
end
An other try: setting the content_type in a post_process filter:
after_post_process :force_content_type_to_pdf
def force_content_type_to_pdf
puts "--------------- Changing content_type"
self.document.instance_write(:content_type, "application/pdf")
end
Here is the controller method to receive and save the file:
def new_upload
#document = Document.create()
document = params[:document]
if (document.nil?)
return
end
#document.document = document
puts "Document type: #{#document.document.content_type}" # logs: 'application/pdf'
puts "Parameters: #{params}" # logs Parameters: {"fooKey"=>"foo", "barKey"=>"bar", "document"=>#<ActionDispatch::Http::UploadedFile:0x007ff5a429be58 #original_filename="upload.pfd", #content_type="application/pdf", #headers="Content-Disposition: form-data; name=\"document\"; filename=\"upload.pfd\"\r\nContent-Type: application/pdf\r\n", #tempfile=#<File:/var/folders/vy/zm_x1bts5hs6pkvzk7clnmvm0000gn/T/RackMultipart20120802-12714-1j0hq6q>>}
#document.foo = params['fooKey']
#document.bar = params['barKey']
if #document.save
render :json => {status: "saved" }
return
else
render json: #document.errors, status: :unprocessable_entity
return
end
end
The file is uploaded, but unreadable. The Finder does not know which application to use to open it.
Here is a screenshot of a QuickLook preview:
The content type is somehow mixed up.
file --mime /file/path/before/or/after/upload.pdf returns the following message on the original file (the one that will be uploaded by the iOS app) or on the file created by the Rails server after a successful upload:
/upload.pfd: application/pdf; charset=binary. Sounds good so far.
mdls -name kMDItemContentType /file/path/before/upload.pdf returns kMDItemContentType = "com.adobe.pdf" on the file to be uploaded. Still ok.
But the same command on the file created by the Rails server returns: kMDItemContentType = "dyn.ah62d4rv4ge81a3xe".
This at least explains why the Finder is confused.
The problem is similar when downloading the file in a browser. Here is the relevant method of my controller:
def download_document
#document = Document.find(params[:id])
if (#document && #document.document)
# Line below propagate the file content-type problem:
send_file Rails.root.join(document.path), :type => "application/pdf", :x_sendfile => false, :stream => false
# This hack works while server is locally hosted
send_data File.read(Rails.root.join(#document.document.path)), :type => "application/pdf"
end
end
Unfortunately, the hack will not be ok when hosting on S3. And it prevents me to conveniently browse my file system to look at the uploaded document when debugging my iOS app.
Downloading the file directly from S3 via an FTP client such as Transmit gets me the same corrupted file.
What is the problem? Where do you think I should further troubleshoot, client or server? How? Any idea, tip, hunch of things to assert or look at?
If you don't have any solution, I would also be glad to be given a temporary fix to set properly again the content_type (or whatever the problem is) on the corrupted file after having downloaded it.
What happens if you name the uploaded file “upload.pdf” instead of “upload.pfd”?