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" />
Related
I'm trying to download a gzip pdf from an url, unpacking it and writing it to a file. It almost works, but currently some characters in the pdf made from my code mismatches the real pdf. I checked this by opening both of the pdf's in notepad.
I provide some short text samples from the two pdfs.
From my code:
’8 /qªMiUe°Ä[H`ðKíulýªäqvA®v8;xÒhÖßÚ²ý!Æ¢ØK$áýçpF[¸t1#y$93
From the real pdf:
ƒ8 /qªMiUe°Ä[H`ðKíulªäqvA®—v8;ŸÒhÖßÚ²!ˆ¢ØK$áçpF[¸t1#y$‘‹3
Here is my code:
public void readPDFfromURL(String urlStr) throws IOException {
URL myURL = new URL(urlStr);
HttpURLConnection urlCon = (HttpURLConnection) myURL.openConnection();
urlCon.setRequestProperty("Accept-Encoding", "gzip");
urlCon.setRequestProperty("Content-Type", "application/pdf");
urlCon.setRequestMethod("GET");
urlCon.setDoInput(true);
urlCon.connect();
Reader reader;
if ("gzip".equals(urlCon.getContentEncoding())) {
reader = new InputStreamReader(new GZIPInputStream(urlCon.getInputStream()));
}
else {
reader = new InputStreamReader(urlCon.getInputStream());
}
FileOutputStream fos = new FileOutputStream("document.pdf");
int data = reader.read();
while(data != -1) {
char c = (char) data;
fos.write(c);
data = reader.read();
}
fos.close();
reader.close();
}
I can open the pdf, and it has the correct amount of pages, but the pages are all blank.
My initial thought is that it might got something to do with character codes to do, like some setting in my java project, intellij etc.
Alternatively, I don't actually need to put it in a file. I just need to download it so I can upload it to another place. However, the pdf should of course be working in either case. I'm really just putting it in an actual file to check if it works.
Thank you for your help!
Here is my new implementation, which solves my question:
public void readPDFfromURL(String urlStr) throws IOException {
URL myURL = new URL(urlStr);
HttpURLConnection urlCon = (HttpURLConnection) myURL.openConnection();
urlCon.setRequestProperty("Accept-Encoding", "gzip");
urlCon.setRequestProperty("Content-Type", "application/pdf");
urlCon.setRequestMethod("GET");
urlCon.setDoInput(true);
urlCon.connect();
GZIPInputStream reader = new GZIPInputStream(urlCon.getInputStream());
FileOutputStream fos = new FileOutputStream("document.pdf");
byte[] buffer = new byte[1024];
int len;
while((len = reader.read(buffer)) != -1){
fos.write(buffer, 0, len);
}
fos.close();
reader.close();
}
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
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.
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();
I have a local .png file that I want to send using POST data to a .php script that will save the data to a .png file on the server. How do I do this? Do I have to encode or something? All I have is a File and a way to POST data.
Here is how I am sending the .png:
public static byte[] imageToByte(File file) throws FileNotFoundException {
FileInputStream fis = new FileInputStream(file);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
try {
for (int readNum; (readNum = fis.read(buf)) != -1;) {
bos.write(buf, 0, readNum);
}
} catch (IOException ex) {
}
byte[] bytes = bos.toByteArray();
return bytes;
}
public static void sendPostData(String url, HashMap<String, String> data)
throws Exception {
URL siteUrl = new URL(url);
HttpURLConnection conn = (HttpURLConnection) siteUrl.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setDoInput(true);
DataOutputStream out = new DataOutputStream(conn.getOutputStream());
Set keys = data.keySet();
Iterator keyIter = keys.iterator();
String content = "";
for (int i = 0; keyIter.hasNext(); i++) {
Object key = keyIter.next();
if (i != 0) {
content += "&";
}
content += key + "=" + URLEncoder.encode(data.get(key), "UTF-8");
}
System.out.println(content);
out.writeBytes(content);
out.flush();
out.close();
BufferedReader in = new BufferedReader(new InputStreamReader(
conn.getInputStream()));
String line = "";
while ((line = in.readLine()) != null) {
System.out.println(line);
}
in.close();
}
The PHP script:
<?
// Config
$uploadBase = "../screenshots/";
$uploadFilename = $_GET['user'] . ".png";
$uploadPath = $uploadBase . $uploadFilename;
// Upload directory
if(!is_dir($uploadBase))
mkdir($uploadBase);
// Grab the data
$incomingData = $_POST['img'];
// Valid data?
if(!$incomingData || !isset($_POST['img']))
die("No input data");
// Write to disk
$fh = fopen($uploadPath, 'w') or die("Error opening file");
fwrite($fh, $incomingData) or die("Error writing to file");
fclose($fh) or die("Error closing file");
echo "Success";
?>
I must admit, I am surprised that you almost get the correct file. Actually, when you send a file using a browser, the form tag has an encoding defined: enctype="multipart/form-data". I don´t know how it works (It is defined in https://www.rfc-editor.org/rfc/rfc2388), but it includes encoding the file (for example, in Base64). Anyhow, you can forget about the internals if you use a http client library like the one from Apache HttpComponents
My minimalistic code works:
$body = file_get_contents('php://input');
$fh = fopen('file.txt', 'w') or die("Error opening fil
e");
fwrite($fh, $body) or die("Error writing to file");
fclose($fh)
curl --upload-file download.txt http://example.com/upload.php
However, set the method to PUT.