Android Code Snippet How to download an image from internet and save in a folder

Problem: download an image from the web in a folder of the app.

Just in case ...

B4X:
job.Download("image_url")

...
Sub JobDone(job As HttpJob)
  If job.Success = True Then
     Dim bmp As Bitmap = job.GetBitmap
      Dim out As OutputStream
      out = File.OpenOutput(File.DirInternal, "avatar.jpg", False)
      bmp.WriteToStream(out, 100, "JPEG")
      out.Close
  end if
  job.Release
end sub

Then if you have a file html in the same folder, you can show the image linked inside the html with a:

B4X:
WebView1.LoadUrl("file://"&File.Combine(File.DirInternal, "index.htm"))

Remember: the image linked in the html <img src=avatar.jpg> won't work if you use webview1.loadhtml(html_string)

Really simple if you have to download just few small images. In case of large files consider other options.

Could be interesting to know how to do it for mp3, pdf, mp4 ... but in any case they are often big files, so consider other solutions.

Some other resources:

image downloader:
https://www.b4x.com/android/forum/t...-simple-way-to-download-images.30875/#content

with download progress:
https://www.b4x.com/android/forum/t...id-downloadmanager-to-download.59840/#content

list of files in a folder:
https://www.b4x.com/android/forum/threads/listfilesonly-without-directories.39541/

Huge files:
https://www.b4x.com/android/forum/threads/download-huge-files-with-httputils2.30220/

Using httputils:
https://www.b4x.com/android/forum/t...ttputils-file-copy2-testing.15718/#post-89278

Download multiple files:
https://www.b4x.com/android/forum/t...les-from-web-server-and-save-on-device.63986/

In the latest link a code to save long files:

B4X:
Dim OutStream AsOutputStreamLog("DownloadReady: "&Job.Tag)
OutStream = File.OpenOutput(File.DirRootExternal, GetFilename(m), False)
File.Copy2(Job.GetInputStream,OutStream) ' save the file
OutStream.Close
 
Last edited:
Top