Downloading to a custom directory

Hello all.

I’ve used LFS to create a custom directory named “Palettes” in my system.DocumentsDirectory, but I can’t figure out how to save data to that folder.

I see the “pathToFile” API, but I’m not sure how to apply it in this case.

I’m retrieving JSON data from a webservice and it’s getting the data fine, just not sure how to steer it into that directory.

Here’s my JSON code from a previous example from way back:

[lua]

– jsonFile() loads json file & returns contents as a string

local jsonFile = function( filename, base )

     

     print("base "…base)

     – set default base dir if none specified

     if not base then base = system.DocumentsDirectory end

     

     – create a file path for corona i/o

     local path = system.pathForFile( filename, base )

     

     – will hold contents of file

     local contents

     

     – io.open opens a file at path. returns nil if no file found

     local file = io.open( path, “r” )

     if file then

          – read all contents of file into a string

          contents = file:read( “*a” )

          io.close( file )    – close the file after using it

     end

     

     return contents

end

[/lua]

The line with

if not base then base = system.DocumentsDirectory end

is where I think I could use a pointer!

Appreciate any help.

-Mario

PS How do I format the code as LUA? The code widget only showed a couple of languages or ‘autodetect’?? :slight_smile:

Line 9 should be something like:
 

local path = system.pathForFile( “Pallets/” … filename, base )

where base is system.DocumentsDirectory

Hmmm, still not getting it. It gives me the same error (I guess I should have posted it earlier)

Cannot create path for resource file “jsonData.json” b/c it does not exist"

So OK, I’m starting from scratch with the network.download example in the API docs:

[lua]

local function networkListener( event )
if ( event.isError ) then
print( “Network error - download failed” )
elseif ( event.phase == “began” ) then
print( “Progress Phase: began” )
elseif ( event.phase == “ended” ) then
print( “displaying response image file” )
myImage = display.newImage( event.response.filename, event.response.baseDirectory, 60, 40 )
myImage.alpha = 0
transition.to( myImage, { alpha = 1.0 } )
end
end

local params = {}
params.progress = true
local filename = “jsonBonus.json”
local base = system.DocumentsDirectory
local path = system.pathForFile( “Palettes/” … filename, base )
network.download(
http://developer.anscamobile.com/demo/hello.png”,
“GET”,
networkListener,
params,
“helloCopy.png”,
path
)

[/lua]

And it STILL gives me an error but as an added bonus, the simulator locks up and crashes. 

Any more clues? Driving me nuts!!

Where is your LFS code that actually created the directory?

[lua]

local json = require “json”
local lfs = require “lfs”
math.randomseed( os.time() )
mRand = math.random
– get raw path to app’s Temporary directory
local temp_path = system.pathForFile( “”, system.DocumentsDirectory )

– change current working directory
local success = lfs.chdir( temp_path ) – returns true on success
local new_folder_path

– Check if folder exists –
function FolderExists(strFolderName)
    local fileHandle, strError = io.open(strFolderName…"\*.*",“r”)
    if fileHandle ~= nil then
        io.close(fileHandle)
        return true
    else
        if string.match(strError,“No such file or directory”) then
            return false
        else
            return true
        end
    end
end

if FolderExists(“Palettes”)then
print(“Directory exists!”)
else
lfs.mkdir( “Palettes” )
new_folder_path = lfs.currentdir() … “\Palettes”
end

[/lua]

And also, where’s the LUA code format option?!?! :slight_smile:

did you do [lua] and [/lua] (without the spaces?) pasting the code in between the tags.

I’m concerned about your FolderExists function.  I’m not sure that file open is doing what you think it does.  I do something like:

[lua]

        local file_path = system.pathForFile( “Pallets”, system.TemporaryDirectory )
        --print(file_path)
        if file_path then

            local file_attr = lfs.attributes( file_path )
            if file_attr then

                 – exists

            else

                 – does not

            end

        end

[/lua]

Maybe you could try that instead?

That part is working as-is. I’ve tested it by deleting the folder, and then re-running the app. It recreates the folder just fine.

It’s the actual download path that’s just NOT getting to that custom directory, the file ALWAYS ends up in the system.DocumentsDirectory.

In this thread http://www.coronalabs.com/blog/2013/02/13/faq-wednesday-sub-folder-and-file-access/ Alberto is having the EXACT same problem I’m having:

"Just another issue:
I’ve created a sub directory in system.DocumentsDirectory and I want to download files directly into that sub-folder I created. When i try and feed it a path other than system base directories, it ignors them and reverts to the default of system.DocumentsDirectory, in spite of adding the subdirectory name.

Is not possible to directly download to the sub-foldr I’ve just created?

Alberto."

Bug? I’d sure hate to have to resort to copying each and every file using the copy function (from that same great thread!) but I’ll do what I have to.

I CAN’T be the only person who’s ever tried to download a file to a custom directory can I!?

Ahem…hello? Anyone? :wink:

How bout this. Using Corona’s own example from network.download: http://docs.coronalabs.com/api/library/network/download.html

How would I save that image into a custom directory?

Hello mroberti and Rob Miracle!

I use this code in Corona 2012.929 to download files directly to a subfolder, and everything runs fine:

local function baixaArquivos() local arqABaixar local docs\_path = system.pathForFile( "", system.DocumentsDirectory ) -- change current working directory local success = lfs.chdir( docs\_path ) local new\_folder\_path local dname = id if success then lfs.mkdir( dname ) new\_folder\_path = lfs.currentdir() .. "/" .. dname .. "/" end local resposta = loadValue("arquivos.data") local array\_arquivos = json.decode(resposta) local num\_arquivos = tonumber(table.maxn(array\_arquivos)) MbBaixados = 0 local function arqDescargado(event) local evento = event if ( evento.isError ) then local alert = native.showAlert( "Aviso", "Hay algún problema con la conexión a internet.\nNo se puede completar la operación.", { "Aceptar" },abortarDescarga) else if num\_arquivos \> 0 then if not descarga\_cancelada then local files\_path = system.pathForFile( id.."/"..array\_arquivos[num\_arquivos+1], system.DocumentsDirectory ) local tamano = lfs.attributes( files\_path, "size" ) MbBaixados = MbBaixados + tamano arqABaixar(array\_arquivos[num\_arquivos]) num\_arquivos = num\_arquivos - 1 else abortarDescarga() end elseif num\_arquivos == 0 then catalogoDescargado(catalogo\_a\_baixar) end end end function arqABaixar(arq) local arquivo = arq local destino = system.pathForFile("",system.DocumentsDirectory) network.download( ruta\_catalogos..dname.."/"..arquivo, "GET", arqDescargado, "/"..id.."/"..arquivo, destino ) end if num\_arquivos \> 0 then arqABaixar(array\_arquivos[num\_arquivos]) num\_arquivos = num\_arquivos - 1 end end

But today I download CoronaSDK-2013.1094 and get this error: Cannot create path for resource file ‘/3/0211605.jpg’. File does not exist.

It seems something has changed in any statment… but what?

Ok.

If I change this line:

network.download( ruta_catalogos…dname…"/"…arquivo, “GET”, arqDescargado, “/”…id…"/"…arquivo, destino )

at arqABaixar function, by:

network.download( ruta_catalogos…dname…"/"…arquivo, “GET”, arqDescargado, “/”…id…"/"…arquivo, system.DocumentsDirectory )

it runs.

I don’t know the reason…

Line 9 should be something like:
 

local path = system.pathForFile( “Pallets/” … filename, base )

where base is system.DocumentsDirectory

Hmmm, still not getting it. It gives me the same error (I guess I should have posted it earlier)

Cannot create path for resource file “jsonData.json” b/c it does not exist"

So OK, I’m starting from scratch with the network.download example in the API docs:

[lua]

local function networkListener( event )
if ( event.isError ) then
print( “Network error - download failed” )
elseif ( event.phase == “began” ) then
print( “Progress Phase: began” )
elseif ( event.phase == “ended” ) then
print( “displaying response image file” )
myImage = display.newImage( event.response.filename, event.response.baseDirectory, 60, 40 )
myImage.alpha = 0
transition.to( myImage, { alpha = 1.0 } )
end
end

local params = {}
params.progress = true
local filename = “jsonBonus.json”
local base = system.DocumentsDirectory
local path = system.pathForFile( “Palettes/” … filename, base )
network.download(
http://developer.anscamobile.com/demo/hello.png”,
“GET”,
networkListener,
params,
“helloCopy.png”,
path
)

[/lua]

And it STILL gives me an error but as an added bonus, the simulator locks up and crashes. 

Any more clues? Driving me nuts!!

Where is your LFS code that actually created the directory?

[lua]

local json = require “json”
local lfs = require “lfs”
math.randomseed( os.time() )
mRand = math.random
– get raw path to app’s Temporary directory
local temp_path = system.pathForFile( “”, system.DocumentsDirectory )

– change current working directory
local success = lfs.chdir( temp_path ) – returns true on success
local new_folder_path

– Check if folder exists –
function FolderExists(strFolderName)
    local fileHandle, strError = io.open(strFolderName…"\*.*",“r”)
    if fileHandle ~= nil then
        io.close(fileHandle)
        return true
    else
        if string.match(strError,“No such file or directory”) then
            return false
        else
            return true
        end
    end
end

if FolderExists(“Palettes”)then
print(“Directory exists!”)
else
lfs.mkdir( “Palettes” )
new_folder_path = lfs.currentdir() … “\Palettes”
end

[/lua]

And also, where’s the LUA code format option?!?! :slight_smile:

did you do [lua] and [/lua] (without the spaces?) pasting the code in between the tags.

I’m concerned about your FolderExists function.  I’m not sure that file open is doing what you think it does.  I do something like:

[lua]

        local file_path = system.pathForFile( “Pallets”, system.TemporaryDirectory )
        --print(file_path)
        if file_path then

            local file_attr = lfs.attributes( file_path )
            if file_attr then

                 – exists

            else

                 – does not

            end

        end

[/lua]

Maybe you could try that instead?

That part is working as-is. I’ve tested it by deleting the folder, and then re-running the app. It recreates the folder just fine.

It’s the actual download path that’s just NOT getting to that custom directory, the file ALWAYS ends up in the system.DocumentsDirectory.

In this thread http://www.coronalabs.com/blog/2013/02/13/faq-wednesday-sub-folder-and-file-access/ Alberto is having the EXACT same problem I’m having:

"Just another issue:
I’ve created a sub directory in system.DocumentsDirectory and I want to download files directly into that sub-folder I created. When i try and feed it a path other than system base directories, it ignors them and reverts to the default of system.DocumentsDirectory, in spite of adding the subdirectory name.

Is not possible to directly download to the sub-foldr I’ve just created?

Alberto."

Bug? I’d sure hate to have to resort to copying each and every file using the copy function (from that same great thread!) but I’ll do what I have to.

I CAN’T be the only person who’s ever tried to download a file to a custom directory can I!?

okayguy.jpgOkay…

Am I doomed? Anyone? Should I file a bug report at this point?

Oops. Double posted!