download file from internet through httpurlconnection method - spring-mvc

I am able to download files from a website . when i run it through java main method, file is downloaded and the response is
Content-Type =application/vnd.openxmlformats-officedocument.wordprocessingml.document
Content-Disposition = attachment;
filename = test.docx
Content-Length = -1
fileName = test.doc
File downloaded
But when i integrate it in my spring mvc application, it doesnt.. i get response as,
Content-Type =text/html; charset=utf-8
content-disposition=null
content-length=-1
the file is not downloaded...
Please help me in getting through this.
Thanks in advance
//code
URL url = new URL(fileURL);
HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
httpConn.setRequestMethod("GET");
httpConn.setRequestProperty("Cookie", "cookie-name");
//add request header
httpConn.setRequestProperty("User-Agent", "test");
int responseCode = httpConn.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK)
{
String fileName = "";
String disposition = httpConn.getHeaderField("Content-Disposition");
String contentType = httpConn.getContentType();
int contentLength = httpConn.getContentLength();
if (disposition != null)
{
// extracts file name from header field
int index = disposition.indexOf("filename=");
if (index > 0) {
fileName = disposition.substring(index + 10,
disposition.length() - 1);
}
}
else
{
// extracts file name from URL
fileName = fileURL.substring(fileURL.lastIndexOf("/") + 1,
fileURL.length());
}
System.out.println("Content-Type = " + contentType);
System.out.println("Content-Disposition = " + disposition);
System.out.println("Content-Length = " + contentLength);
System.out.println("fileName = " + fileName);
// opens input stream from the HTTP connection
InputStream inputStream = httpConn.getInputStream();
String saveFilePath = "E:/" + fileName;
// opens an output stream to save into file
FileOutputStream outputStream = new FileOutputStream(saveFilePath);
int bytesRead = -1;
byte[] buffer = new byte[BUFFER_SIZE];
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.close();
inputStream.close();
System.out.println("File downloaded");
}
else
{
System.out.println("No file to download"):
}
httpConn.disconnect();

I got it worked. It seems that there was problem in the url which i called to download file. The url itself returned print response not download response that is why it was not working.
mistake was from my end...
Thanks to all who tried to help me.

Related

How to force download a file from server in iphone browser

String filePath = "http://images.all-free-download.com/images
/graphiclarge/baby_child_girl_215819.jpg";
The above String is my download path.
URL url = new URL(filePath);
HttpURLConnection httpConn = (HttpURLConnection)
url.openConnection();
InputStream inStream = httpConn.getInputStream();
// if you want to use a relative path to context root:
#SuppressWarnings("unused")
String relativePath = getServletContext().getRealPath("");
// obtains ServletContext
ServletContext context = getServletContext();
// gets MIME type of the file
String mimeType = context.getMimeType(filePath);
if (mimeType == null) {
// set to binary type if MIME mapping not found
mimeType = "application/octet-stream";
}
// modifies response
response.setContentType(mimeType);
response.setContentLength((int) httpConn.getContentLength());
String fileName = filePath.substring(filePath.lastIndexOf("/") +
1,
filePath.length());
// forces download
//String headerKey = "Content-Disposition";
//String headerValue = String.format("attachment;
filename=\"%s\"", fileName);
response.setHeader("Content-Transfer-Encoding", "binary");
response.setHeader("Content-Disposition","attachment;
filename=\""+ fileName);
//response.setHeader(headerKey, headerValue);
// obtains response's output stream
OutputStream outStream = response.getOutputStream();
byte[] buffer = new byte[4096];
int bytesRead = -1;
while ((bytesRead = inStream.read(buffer)) != -1) {
outStream.write(buffer, 0, bytesRead);
}
inStream.close();
outStream.close();
The above code working fine for android device in all browser. But its not working in iphone.
Once click download button, the image directly display. Not asking anythink.
I want store the image to gallary in iphone.
Can any one pls help me.Is it possible for iphone.

Pdf Download but not Opening decoding error

This is my jsp we are calling an java method
<%
PDFFileUploader.generatePDcFile(); //Calls the PDF method;
%>
This is my PDFFileUploader code
public class PDFFileUploader {
static final String UPLOAD_URL = "http://localhost:7080/pdf/GetPDFFile";
static final int BUFFER_SIZE = 4096;
public static void generatePDcFile() throws IOException
{
System.out.println("Inside generatePDC File");
// takes file path from first program's argument
String filePath = "H:/report1.pdf";
File uploadFile = new File("H:/report1.pdf");
System.out.println("File to upload: " + filePath);
// creates a HTTP connection
URL url = new URL(UPLOAD_URL);
HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
httpConn.setUseCaches(false);
httpConn.setDoOutput(true);
httpConn.setRequestMethod("POST");
// sets file name as a HTTP header
httpConn.setRequestProperty("fileName", uploadFile.getName());
// opens output stream of the HTTP connection for writing data
OutputStream outputStream = httpConn.getOutputStream();
// Opens input stream of the file for reading data
FileInputStream inputStream = new FileInputStream(uploadFile);
byte[] buffer = new byte[BUFFER_SIZE];
int bytesRead = -1;
System.out.println("Start writing data...");
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
System.out.println("Data was written.");
outputStream.close();
inputStream.close();
//Read pdc file
//FileOutputStream test = new FileOutputStream("test");
// always check HTTP response code from server
InputStream test = null;
File pdcFile = new File("H:/report123.pdf");
FileOutputStream outputStreamTest = new FileOutputStream(pdcFile);
//byte[] bufferTest = new byte[BUFFER_SIZE];
//int bytesReadTest = -1;
//final OutputStream ostream = new FileOutputStream("/tmp/data.pdc");
int responseCode = httpConn.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
// reads server's response
/* BufferedReader reader = new BufferedReader(new InputStreamReader(
httpConn.getInputStream()));*/
test = httpConn.getInputStream();
String message= httpConn.getResponseMessage();
System.out.println("Message is///"+message);
System.out.println("Header :: "+httpConn.getHeaderField(0));
final byte[] bufferTest = new byte[1024*14];
while (true) {
int len = test.read(bufferTest);
if (len <= 0) {
break;
}
outputStreamTest.write(bufferTest, 0, len);
}
outputStreamTest.close();
test.close();
String fileName = "";
String disposition = httpConn.getHeaderField("Content-Disposition");
// extracts file name from header field
int index = disposition.indexOf("filename=");
if (index > 0) {
fileName = disposition.substring(index + 10,
disposition.length() - 1);
}
System.out.println("Get File Name"+fileName);
/* Map<String, List<String>> map = httpConn.getHeaderFields();
for (Map.Entry<String, List<String>> entry : map.entrySet()) {
System.out.println("Key : " + entry.getKey() +
" ,Value : " + entry.getValue());
}*/
// String response = reader.readLine();
//System.out.println("Server's response: " + response);
} else {
System.out.println("Server returned non-OK code: " + responseCode);
}
}
from here a servlet is called through the URL provided above the code for doPost method for the getPDFFile Servlet is
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
// Gets file name for HTTP header
String fileName = request.getHeader("fileName");
File saveFile = new File(SAVE_DIR + fileName);
// prints out all header values
System.out.println("===== Begin headers =====");
Enumeration<String> names = request.getHeaderNames();
while (names.hasMoreElements()) {
String headerName = names.nextElement();
System.out.println(headerName + " = " + request.getHeader(headerName));
}
System.out.println("===== End headers =====\n");
// opens input stream of the request for reading data
InputStream inputStream = request.getInputStream();
// opens an output stream for writing file
/*FileOutputStream outputStream = new FileOutputStream(saveFile);*/
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
byte[] buffer = new byte[BUFFER_SIZE];
int bytesRead = -1;
System.out.println("Receiving data...");
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
System.out.println("Data received.");
outputStream.close();
inputStream.close();
System.out.println("File written to: " + saveFile.getAbsolutePath());
int processStatus = 0;
//temp file (used for conversion)
/* boolean success = (new File
(saveFile.getAbsolutePath())).delete();
System.out.println("File deleted :: "+success);
//delete pdc file too
boolean successtemp = (new File
(recentlyConvertedFile.getAbsolutePath())).delete();
System.out.println("File deleted :: "+successtemp);*/
response.setContentType("application/octet-stream" );
response.setHeader("Content-Disposition","inline;filename=\"" + saveFile.getName() + "\"");
response.setContentLength((int) saveFile.length());
OutputStream os = response.getOutputStream();
FileInputStream fis = new FileInputStream(saveFile);
//op.write(response.toString().getBytes(Charset.forName("utf-8")));
//op.flush();
try {
int byteRead = 0;
while ((byteRead = fis.read()) != -1) {
os.write(buffer, 0, byteRead);
}
os.flush();
} catch (Exception excp) {
excp.printStackTrace();
} finally {
os.close();
fis.close();
}
// sends response to client
//response.getWriter().print("UPLOAD DONE");
}
The file is getting downloaded but not opening the generated pdf have the same size of the original and I have taken a text file and printed the content to another file it seems to read only first line of the text file taken as input
Your final loop returning a file from the servlet to the client looks like this:
while ((byteRead = fis.read()) != -1) {
os.write(buffer, 0, byteRead);
}
You seem to have forgotten to use buffer in the fis.read() which should look like this:
while ((byteRead = fis.read(buffer)) != -1) {
os.write(buffer, 0, byteRead);
}
Thus, you send back as many copies of the buffer contents as fis returns numbers != -1.
BTW: Your servlet puts the data it receives into the ByteArrayOutputStream outputStream and drops that, but it claims to have written them into the file it eventually attempts to return to the caller.

Problems with downloading pdf file from web api service

I'm trying to set up a web api service that searches for a .pdf file in a directory and returns the file if it's found.
The controller
public class ProductsController : ApiController
{
[HttpPost]
public HttpResponseMessage Post([FromBody]string certificateId)
{
string fileName = certificateId + ".pdf";
var path = #"C:\Certificates\20487A" + fileName;
//check the directory for pdf matching the certid
if (File.Exists(path))
{
//if there is a match then return the file
HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
var stream = new FileStream(path, FileMode.Open);
stream.Position = 0;
result.Content = new StreamContent(stream);
result.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment") { FileName = fileName };
result.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/pdf");
result.Content.Headers.ContentDisposition.FileName = fileName;
return result;
}
else
{
HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.Gone);
return result;
}
}
}
I'm calling the service with the following code
private void GetCertQueryResponse(string url, string serial)
{
string encodedParameters = "certificateId=" + serial.Replace(" ", "");
HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create(url);
httpRequest.Method = "POST";
httpRequest.ContentType = "application/x-www-form-urlencoded";
httpRequest.AllowAutoRedirect = false;
byte[] bytedata = Encoding.UTF8.GetBytes(encodedParameters);
httpRequest.ContentLength = bytedata.Length;
Stream requestStream = httpRequest.GetRequestStream();
requestStream.Write(bytedata, 0, bytedata.Length);
requestStream.Close();
HttpWebResponse response = (HttpWebResponse)httpRequest.GetResponse();
if (response.StatusCode == HttpStatusCode.OK)
{
byte[] bytes = null;
using (Stream stream = response.GetResponseStream())
using (MemoryStream ms = new MemoryStream())
{
int count = 0;
do
{
byte[] buf = new byte[1024];
count = stream.Read(buf, 0, 1024);
ms.Write(buf, 0, count);
} while (stream.CanRead && count > 0);
ms.Position = 0;
bytes = ms.ToArray();
}
var filename = serial + ".pdf";
Response.ContentType = "application/pdf";
Response.Headers.Add("Content-Disposition", "attachment; filename=\"" + filename + "\"");
Response.BinaryWrite(bytes);
}
}
This appears to be working in the sense that the download file dialogue is shown with the correct file name and size etc, but the download takes only a couple of seconds (when the file sizes are >30mb) and the files are corrupt when I try to open them.
Any ideas what I'm doing wrong?
Your code looks similar to what Ive used in the past, but below is what I typically use:
Response.AddHeader("content-length", myfile.Length.ToString())
Response.AddHeader("content-disposition", "inline; filename=MyFilename")
Response.AddHeader("Expires", "0")
Response.AddHeader("Pragma", "Cache")
Response.AddHeader("Cache-Control", "private")
Response.ContentType = "application/pdf"
Response.BinaryWrite(finalForm)
I post this for 2 reasons. One, add the content-length header, you may have to indicate how large the file is so the application waits for the whole response.
If that doesn't fix it. Set a breakpoint, does the byte array content the appropriate length (aka, 30 million bytes for a 30 MB file)? Have you used fiddler to see how much content is coming back over the HTTP call?

Google Drive api uploads file name as "Untitled"

I can upload file to google drive from my website, but my problem is it will show the file as Untitled after uploading.
How can I add or post title to the uploading file.
Thanks,
My Code:
public string UploadFile(string accessToken, byte[] file_data, string mime_type)
{
try
{
string result = "";
byte[] buffer = file_data;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://www.googleapis.com/upload/drive/v2/files?uploadType=media");
request.Method = "POST";
request.ContentType = mime_type;
request.ContentLength = buffer.Length;
request.Headers.Add(HttpRequestHeader.Authorization, "Bearer " + accessToken);
var stream = request.GetRequestStream();
stream.Write(file_data, 0, file_data.Length);
stream.Close();
HttpWebResponse webResponse = (HttpWebResponse)request.GetResponse();//Get error here
if(webResponse.StatusCode == HttpStatusCode.OK)
{
Stream responseStream = webResponse.GetResponseStream();
StreamReader responseStreamReader = new StreamReader(responseStream);
result = responseStreamReader.ReadToEnd();//parse token from result
var jLinq = JObject.Parse(result);
JObject jObject = JObject.Parse(jLinq.ToString());
webResponse.Close();
return jObject["alternateLink"].ToString();
}
return string.Empty;
}
catch
{
return string.Empty;
}
}
I used RestSharp for uploading a file to google drive.
public static void UploadFile(string accessToken, string parentId)
{
var client = new RestClient { BaseUrl = new Uri("https://www.googleapis.com/") };
var request = new RestRequest(string.Format("/upload/drive/v2/files?uploadType=multipart&access_token={0}", accessToken), Method.POST);
var bytes = File.ReadAllBytes(#"D:\mypdf.pdf");
var content = new { title = "mypdf.pdf", description = "mypdf.pdf", parents = new[] { new { id = parentId } }, mimeType = "application/pdf" };
var data = JsonConvert.SerializeObject(content);
request.AddFile("content", Encoding.UTF8.GetBytes(data), "content", "application/json; charset=utf-8");
request.AddFile("mypdf.pdf", bytes, "mypdf.pdf", "application/pdf");
var response = client.Execute(request);
if (response.StatusCode != HttpStatusCode.OK) throw new Exception("Unable to upload file to google drive");
}
Doing it with out using the google.apis dlls isnt that easy. You need to send the meta data before you send the rest of the file. For that you need to use uploadType=multipart
https://developers.google.com/drive/manage-uploads#multipart
This should get you started sorry its a wall of code. I havent had time to create a tutorial for this yet.
FileInfo info = new FileInfo(pFilename);
//Createing the MetaData to send
List<string> _postData = new List<string>();
_postData.Add("{");
_postData.Add("\"title\": \"" + info.Name + "\",");
_postData.Add("\"description\": \"Uploaded with SendToGoogleDrive\",");
_postData.Add("\"parents\": [{\"id\":\"" + pFolder + "\"}],");
_postData.Add("\"mimeType\": \"" + GetMimeType(pFilename).ToString() + "\"");
_postData.Add("}");
string postData = string.Join(" ", _postData.ToArray());
byte[] MetaDataByteArray = Encoding.UTF8.GetBytes(postData);
// creating the Data For the file
byte[] FileByteArray = System.IO.File.ReadAllBytes(pFilename);
string boundry = "foo_bar_baz";
string url = "https://www.googleapis.com/upload/drive/v2/files?uploadType=multipart" + "&access_token=" + myAutentication.accessToken;
WebRequest request = WebRequest.Create(url);
request.Method = "POST";
request.ContentType = "multipart/related; boundary=\"" + boundry + "\"";
// Wrighting Meta Data
string headerJson = string.Format("--{0}\r\nContent-Type: {1}\r\n\r\n",
boundry,
"application/json; charset=UTF-8");
string headerFile = string.Format("\r\n--{0}\r\nContent-Type: {1}\r\n\r\n",
boundry,
GetMimeType(pFilename).ToString());
string footer = "\r\n--" + boundry + "--\r\n";
int headerLenght = headerJson.Length + headerFile.Length + footer.Length;
request.ContentLength = MetaDataByteArray.Length + FileByteArray.Length + headerLenght;
Stream dataStream = request.GetRequestStream();
dataStream.Write(Encoding.UTF8.GetBytes(headerJson), 0, Encoding.UTF8.GetByteCount(headerJson)); // write the MetaData ContentType
dataStream.Write(MetaDataByteArray, 0, MetaDataByteArray.Length); // write the MetaData
dataStream.Write(Encoding.UTF8.GetBytes(headerFile), 0, Encoding.UTF8.GetByteCount(headerFile)); // write the File ContentType
dataStream.Write(FileByteArray, 0, FileByteArray.Length); // write the file
// Add the end of the request. Start with a newline
dataStream.Write(Encoding.UTF8.GetBytes(footer), 0, Encoding.UTF8.GetByteCount(footer));
dataStream.Close();
try
{
WebResponse response = request.GetResponse();
// Get the stream containing content returned by the server.
dataStream = response.GetResponseStream();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader(dataStream);
// Read the content.
string responseFromServer = reader.ReadToEnd();
// Display the content.
//Console.WriteLine(responseFromServer);
// Clean up the streams.
reader.Close();
dataStream.Close();
response.Close();
}
catch (Exception ex)
{
return "Exception uploading file: uploading file." + ex.Message;
}
If you need any explinations beyond the comments let me know. I strugled to get this working for a month. Its almost as bad as resumable upload.
I was searching for the solution of the given problem and previously I was putting uploadType=resumable that causes the given issue and when I used uploadType=multipart problem is resolved...

Downloading file on client side using absolute path .NET

string FilePath = HttpUtility.UrlDecode(Request.QueryString.ToString());
string[] s = FilePath.Split(new char[] { ',' });
string path = s[0];
string FileName = s[1];
String str = HttpContext.Current.Request.Url.AbsolutePath;
System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
response.ClearContent();
response.Clear();
// response.ContentType = "text/plain";
response.AddHeader("Content-Disposition", "attachment; filename=" + FileName+ ";");
response.TransmitFile(path+FileName);
response.Flush();
response.End();
Above is the code in which i get location of audio file from another page . the audio file is located on a remote machine which is accesible using url e.g. http:\servername\audiofiles\filename.wav . response.Transmit and .WriteFile requires virtual path whereas response.Write() does not download file . How can i give the absolute url instead of virtual path to download file
Found the answer my self from another place :
string FilePath = HttpUtility.UrlDecode(Request.QueryString.ToString());
string[] s = FilePath.Split(new char[] { ',' });
string path = s[0];
string FileName = s[1];
int bytesToRead = 10000;
byte[] buffer = new Byte[bytesToRead];
try
{
HttpWebRequest fileReq = (HttpWebRequest)HttpWebRequest.Create(path+FileName);
HttpWebResponse fileResp = (HttpWebResponse)fileReq.GetResponse();
if (fileReq.ContentLength > 0)
fileResp.ContentLength = fileReq.ContentLength;
stream = fileResp.GetResponseStream();
var resp = HttpContext.Current.Response;
resp.ContentType = "application/octet-stream";
resp.AddHeader("Content-Disposition", "attachment; filename=\"" + FileName + "\"");
resp.AddHeader("Content-Length", fileResp.ContentLength.ToString());
int length;
do
{
if (resp.IsClientConnected)
{
// Read data into the buffer.
length = stream.Read(buffer, 0, bytesToRead);
// and write it out to the response's output stream
resp.OutputStream.Write(buffer, 0, length);
resp.Flush();
//Clear the buffer
buffer = new Byte[bytesToRead];
}
else
{
// cancel the download if client has disconnected
length = -1;
}
} while (length > 0); //Repeat until no data is read
}
finally
{
if (stream != null)
{
//Close the input stream
stream.Close();
}
}
}

Resources