I get image link from the server and on click of the link it should download and save it to the gallery, I have no clue on how to do it. please help me on this, thanks in advance
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
**combine the below code to store image at a particula path**
File storagePath = new File(Environment
.getExternalStorageDirectory()
+ "/com.logistics.herestethiparty/images/");
storagePath.mkdirs();
File file = new File(storagePath, fileImageName);
**i have used the below code in asyncclass for image download**
URL url = new URL(imageUrl);
HttpURLConnection urlConnection = (HttpURLConnection) url
.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
urlConnection.connect();
FileOutputStream fileOutput = new FileOutputStream(file);
InputStream inputStream = urlConnection.getInputStream();
int downloadedSize = 0;
byte[] buffer = new byte[1024];
int bufferLength = 0;
while ((bufferLength = inputStream.read(buffer)) > 0) {
fileOutput.write(buffer, 0, bufferLength);
downloadedSize += bufferLength;
}
// close the output stream when done
fileOutput.close();
回答2:
Try this code, Call mDownloadAndSave()
method for save image on SDCard, it will solve your problem.
public void mDownloadAndSave() {
// Setting up file to write the image to.
File f = new File("/mnt/sdcard/img.png");
// Open InputStream to download the image.
InputStream is;
try {
is = new URL("http://www.tmonews.com/wp-content/uploads/2012/10/androidfigure.jpg").openStream();
// Set up OutputStream to write data into image file.
OutputStream os = new FileOutputStream(f);
CopyStream(is, os);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void CopyStream(InputStream is, OutputStream os) {
final int buffer_size = 1024;
try {
byte[] bytes = new byte[buffer_size];
for (;;) {
int count = is.read(bytes, 0, buffer_size);
if (count == -1)
break;
os.write(bytes, 0, count);
}
} catch (Exception ex) {
}
}
And Don't forget to add below permission into Androidmanifest.xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>