Im trying to get image using webservice and saved to sd card. The file saved but i couldnt open the file. Once i open the file it saying "could not load image". Below is my code.
httpTransport.call(SOAP_ACTION, envelope);
Object response = envelope.getResponse();
test = response.toString();
Blob picture = org.hibernate.Hibernate.createBlob(test.replaceAll("-", "").getBytes());
String FILENAME = "voucher1.jpg";
File root = Environment.getExternalStorageDirectory();
FileOutputStream f = new FileOutputStream(new File(root, FILENAME));
InputStream x=picture.getBinaryStream();
int size=x.available();
byte b[]= new byte[size];
x.read(b);
f.write(b);
f.close();
Please help. Thanks
I changed the format..instead use web service i just use the image url to retrieve the image and it works...
i try this and its work fine. Thanks.
URL url = new URL(fileURL);
URLConnection conexion = url.openConnection();
conexion.connect();
int lenghtOfFile = conexion.getContentLength();
Log.d("ANDRO_ASYNC", "Lenght of file: " + lenghtOfFile);
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream("/sdcard/caldophilus.jpg");
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
i assume you need to call f.flush() in order to write out all data in stream to file.
f.flush();
f.close();
Related
I had written a program to get stocks data from yahoo finance website, my code used to work previously, lately it has stopped working.
When i access the same url from browser a file is downloaded,
however from java code i get and empty stream
here is sample link
These are the codes that i have tried
try{
ReadableByteChannel rbc = Channels
.newChannel(website.openStream());
FileOutputStream fos;
fos = new FileOutputStream(Type+"//"+
FileName + ".csv");
fos.getChannel().transferFrom(rbc, 0,
Long.MAX_VALUE);
fos.flush();
fos.close();
String fileName = "file.txt"; //The file that will be saved on your computer
URL link = new URL(website.toString());
//Code to download
InputStream in = new BufferedInputStream(link.openStream());
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
int n = 0;
while (-1!=(n=in.read(buf)))
{
out.write(buf, 0, n);
}
out.close();
in.close();
byte[] response = out.toByteArray();
FileOutputStream fos = new FileOutputStream(fileName);
fos.write(response);
fos.close();
//End download code
Runnable r1 = new Analyzer(Type+"//"+
FileName + ".csv",Type,Name);
Thread r2= new Thread(r1);
r2.start();
r2.join();
}
catch(Exception e)
{
e.getMessage();
}
i want to download video from URL my function is as below
String fileURL = "http://192.168.1.2/UserFiles/Videos/OutputVideo/Birthday%20Bash5tV3fgjf4Sfi11sC.mp4";
String fileName = "Abc.mp4";
public void downloadFile(String fileURL, String fileName){
Toast.makeText(getApplicationContext(), "Download File", Toast.LENGTH_LONG).show();
try
{
URL u = new URL(fileURL);
URLConnection ucon = u.openConnection();
//Define InputStreams to read from the URLConnection.
// uses 3KB download buffer
File file =new File(Environment.getExternalStorageDirectory() + File.separator + "/Planetskool/Media/Videos/"+fileName);
InputStream is = ucon.getInputStream();
BufferedInputStream inStream = new BufferedInputStream(is, 1024 * 5);
FileOutputStream outStream = new FileOutputStream(file);
byte[] buff = new byte[5 * 1024];
//Read bytes (and store them) until there is nothing more to read(-1)
int len;
while ((len = inStream.read(buff)) != -1)
{
outStream.write(buff,0,len);
}
//clean up
outStream.flush();
outStream.close();
inStream.close();
}
catch (Exception se)
{
se.printStackTrace();
}
}
its downloading video in 0kb whats wrong with this
use async method to download file from URL.
Three things might be happened
Missing Internet permission
Missing Write external storage permission
"/Planetskool/Media/Videos/" Directory not exist, Create dir first.
http://192.168.1.2 it is not internet URL check your URL
My Android app has a Webview to access to my website. I noticed in the server that when a file is downloaded by the app the bandwidth used is less than when is downloaded by another device or browser.
In method onDownloadStart I call to an AsyncTask class:
protected String doInBackground(String... sUrl) {
try {
URL url = new URL(sUrl[0]);
//Getting directory to store the file
//Connection handler
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setDoOutput(true);
connection.connect();
//Obtaining filename
File outputFile = new File(directory, filename);
InputStream input = new BufferedInputStream(connection.getInputStream());
OutputStream output = new FileOutputStream(outputFile);
byte buffer[] = new byte[1024];
int bufferLength = 0;
int total = 0;
while ((bufferLength=input.read(buffer))!=-1) {
total += bufferLength;
output.write(buffer, 0, bufferLength);
}
connection.disconnect();
output.flush();
output.close();
input.close();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
Files downloaded are empty altough their filename and format are correct and I receive HTTP 200 message from the server; also execution does not enter into the while loop. I have tried to change buffer size and the problem is not solved.
I've followed what is written in many similar questions but there is still a problem
From a jsp I get a pdf, if i go to the URL the browser opens automatically the pdf, jsp page does something like:
//Gets the pdf from the database
BufferedInputStream bis = new BufferedInputStream(file.getBinaryStream(), buffer);
ByteArrayOutputStream baos=new ByteArrayOutputStream();
int readed=0;
while ((readed=bis.read())!=-1) baos.write(readed);
bis.close();
byte[] pdf=baos.toByteArray();
response.setContentType("application/pdf");
response.setContentLength(pdf.length);
response.getOutputStream().write(pdf, 0, pdf.length);
This code works because if we browse to the URL we get the PDF into the browser.
Then in Android I do in an AsyncTask:
InputStream is = null;
try {
URL url = new URL(myurl); // <-- this is the same URL tested into browser
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
urlConnection.connect();
FileOutputStream fos = new FileOutputStream(getWorkingDir()+fileName);
InputStream inputStream = urlConnection.getInputStream();
int totalSize = urlConnection.getContentLength(); //<- this seems to be incorrect, totalSize value is 22 but file is more than 50Kb length
int downloadedSize = 0;
byte[] buffer = new byte[1024];
int bufferLength = 0; //used to store a temporary size of the buffer
while ( (bufferLength = inputStream.read(buffer)) >=0) {
fos.write(buffer, 0, bufferLength);
downloadedSize += bufferLength;
// at this point downloadedSize is only 2, and next iteration in while exists so a file os size 2bytes is created...
}
fos.close();
Of course I've the permission to write in SD and use Internet in the AndrodiManifest.xml
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
I've tried directly with URLConnection, getting the InputStream and we get the same, only reading 2 bytes...
Write to external file is working, if I try to write a string.getBytes() to a file it's written.
If we get conn.getResponseCode() it's 200, so it's ok.
The same .jsp can according to parameters return a list of documents (in JSON) or a PDF if we provide his database ID, if we get the list of pdf, it works, in this case it's readed like:
reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
stringBuilder = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
stringBuilder.append(line);
}
Any idea why is not working when it tries to get the binary pdf file?
Where is the failure?
Thanks for your expertice...
Its working for me Try to modify this :
private void savePrivateExternalFile(String fileURL, String fName) {
HttpURLConnection connection = null;
URL url = null;
try {
url = new URL(fileURL);
connection = (HttpURLConnection) url.openConnection();
connection.addRequestProperty(BConstant.WEB_SERVICES_COOKIES,
cookie);
connection.setDoOutput(true);
connection.connect();
} catch (IOException e1) {
e1.printStackTrace();
}
File folderDir = null;
folderDir = new File(getExternalFilesDir("Directory Name") + "/Files");
File file = new File(folderDir, fName);
if (file.exists()) {
file.delete();
}
if ((folderDir.mkdirs() || folderDir.isDirectory())) {
try {
InputStream inputStream = connection.getInputStream();
BufferedInputStream bufferedInputStream = null;
bufferedInputStream = new BufferedInputStream(inputStream,
1024 * 5);
FileOutputStream fileOutputStream = new FileOutputStream(
folderDir + "/" + fName);
byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = inputStream.read(buffer)) != -1) {
fileOutputStream.write(buffer, 0, len1);
}
bufferedInputStream.close();
fileOutputStream.close();
inputStream.close();
connection.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
}
Use this if you want to open Downloaded file :
File file = new File(getExternalFilesDir("Directory Name")+ "/Files/" + fileName);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(file),"application/pdf");
intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
startActivity(intent);
Add this line in your Manifest file:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
I am having a text file in GAE blob store already. I tried to access that file from android and save it into SD card.
String filename = 'HelloWorld.txt';
String fileURL = "http://bakupand.appspot.com/download?blob-key=AMIfv95pR-81U2oXcOQ1wkj_6iwKsfRkb7Eah6LYpdN08KTeHM0Db2FUCHRHP-ijs0qVc8UFnGSeH4Tu1RlcQCn9d3gkvZK8v9FCl09aknEztvL7xEpTgS2ptL0liAxQThiyKz6SQJa_-M-9MRS8WoKzgWmZxU_ReSZ0ZSVCcubdpPoi5HFPL1w";
try {
File sdCard = Environment.getExternalStorageDirectory();
File dir = new File(sdCard.getAbsolutePath() + "/doc");
dir.mkdirs();
URL u = new URL(fileURL);
HttpURLConnection c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
FileOutputStream f = new FileOutputStream(new File(dir, filename));
InputStream in = c.getInputStream();
byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = in.read(buffer)) > 0) {
f.write(buffer, 0, len1);
}
f.close();
} catch (Exception e) {
e.printStackTrace();
Log.d("Downloader", e.getMessage());
}
But facing IO FileNotFoundException for the above code.
05-12 19:25:49.067: W/System.err(15327): java.io.FileNotFoundException: http://bakupand.appspot.com/download?blob-key=AMIfv95pR-81U2oXcOQ1wkj_6iwKsfRkb7Eah6LYpdN08KTeHM0Db2FUCHRHP-ijs0qVc8UFnGSeH4Tu1RlcQCn9d3gkvZK8v9FCl09aknEztvL7xEpTgS2ptL0liAxQThiyKz6SQJa_-M-9MRS8WoKzgWmZxU_ReSZ0ZSVCcubdpPoi5HFPL1w
Cane anyone help me on this? Thanks in advance.
Note: I could access the that file from browser with the same url.