download file from url in gwt - gwt

I want to download a file from internet and I have url of that file . so I wrote a download servlet :
public class DownloadServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException {
String pathToDownload = request.getParameter("url");
URL url = new URL(pathToDownload);
URLConnection uc = url.openConnection();
String contentType = uc.getContentType();
int contentLength = uc.getContentLength();
InputStream is = uc.getInputStream();
response.setContentType(contentType);
// resp.setHeader("Content-Disposition", "attachment; filename*=\"utf-8''" + filename + "");
ServletOutputStream os = response.getOutputStream();
byte[] b = new byte[2048];
int length;
while ((length = is.read(b)) != -1) {
os.write(b, 0, length);
}
is.close();
os.close();
}
}
in this i want to show the popup when user clicks on file whether to save or not so there is
resp.setHeader("Content-Disposition", "attachment; filename*=\"utf-8''" + filename + "");
but I want the filename same as filename on internate so additionally what is needed in above snippet?

Cut substring from the last "/" to the end of the URL string - this is your file name.

String disposition = httpConn.getHeaderField("Content-Disposition");
if (disposition != null) {
// extracts file name from header field
int index = disposition.indexOf("filename=");
if (index != 0) {
fileName = disposition.substring(index + 9,
disposition.length());
}
} else {
// extracts file name from URL
fileName = link.substring(link.lastIndexOf("/") + 1,
link.length());
}

Related

POST request using form-data in body with core java, getting bad request

I have written an core java code to post call with form-data(always pdf) along with Auth but i am always getting bad request.enter image description here
public class POSTAPIClientSucessFile2 {
public static void main(String[] args) throws IOException {
try {
String boundary = "";
final String LINE_FEED = "\r\n";
HttpURLConnection httpConn;
OutputStream outputStream;
PrintWriter writer;
String authData = "Bearer 3AAABLblqZhAmXYU1afunO0RBkBBOxDcE0elkSXa6WmNorjjNNGoWjQF5f_mnl21GVK4bOGjsIzqNNB1ZLLLZol--21hmnI1w";
// creates a unique boundary based on time stamp
boundary = "===" + System.currentTimeMillis() + "===";
URL url = new URL("https://api.na3.echosign.com/api/rest/v6/transientDocuments");
System.out.println("URL : " + url.toString());
httpConn = (HttpURLConnection) url.openConnection();
httpConn.setUseCaches(false);
httpConn.setDoOutput(true); // indicates POST method
httpConn.setDoInput(true);
httpConn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
httpConn.addRequestProperty("Authorization", authData);
outputStream = httpConn.getOutputStream();
writer = new PrintWriter(new OutputStreamWriter(outputStream, "UTF-8"), true);
String fileName = "C:/delete/test.pdf";
//String fieldName = "File";
writer.append("--" + boundary).append(LINE_FEED);
writer.append("Content-Disposition: form-data; name=\"File\"; filename=\"/C:/delete/test.pdf\"").append(LINE_FEED);
writer.append("Content-Type: application/pdf").append(LINE_FEED);
writer.append("Content-Transfer-Encoding: binary").append(LINE_FEED);
writer.append(LINE_FEED);
writer.flush();
int responseCode = ((HttpURLConnection) httpConn).getResponseCode();
System.out.println("responseCode --> "+responseCode);
System.out.println("response msg--> "+((HttpURLConnection) httpConn).getResponseMessage());
System.out.println("response --> "+((HttpURLConnection) httpConn).toString());
FileInputStream inputStream = new FileInputStream(fileName);
byte[] buffer = new byte[4096];
int bytesRead = -1;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.flush();
inputStream.close();
writer.append(LINE_FEED);
writer.flush();
} catch (Exception e) {
e.printStackTrace();
}
}
}
always getting bad request even by changing the content-type
enter image description here

POST multipart/form-data contents out of order

I am trying to build a web server using java sockets, everything is fine except when the browser sends POST request with file attached, when the request is received the content of the file is out of order , the file sent was txt file with line numbers when received the line numbers were out of order. is there any way I can avoid this I want ordered data (see pic 99522 is followed by 99712) THANKs
public class Server{
public static void main(String[] args) throws IOException {
ServerSocket server = new ServerSocket(8080);
while(true) new Thread(new Client(server.accept())).start();
}
}
class Client implements Runnable {
Socket client;
OutputStream os = new FileOutputStream(new File("File12"));
InputStream in;
OutputStream out;
static ArrayList<Socket> clients = new ArrayList<Socket>();
String index;
String response;
Client(Socket client) throws IOException {
String listOfFiles = "<ol>";
this.client = client;
in = client.getInputStream();
out = client.getOutputStream();
clients.add(client);
for (File file : new File(".").listFiles()) if (file.isFile()) listOfFiles += "<li>" + file.getName() + "</li>";
listOfFiles += "</ol>";
index = "<!DOCTYPE html><html><body><h1>" + new Date() + "</h1><hr>"+listOfFiles+"<form id='upload' enctype='multipart/form-data' method='post' action='/upload'><input id='fileupload' multiple name='myfile' type='file' /><input type='submit' value='submit' id='submit' /></form></body></html>";
response = "HTTP/1.1 200 OK\r\n" +
"Content-Type: text/html\r\n" +
"Content-Length:"+index.length()+"\r\n" +
"\r\n" +
index;
}
public void run() {
try {
String msg = "";
byte buffer[] = new byte[32*1024];
int read = in.read(buffer);
while(read != -1){
msg = new String(buffer);
System.out.println(msg);
if(msg.startsWith("POST")){
System.err.println("RAN IN POST");
out.write("HTTP/1.1 200 OK\r\n".getBytes());
out.write("Content-Type: text/plain\r\n".getBytes());
out.write(("Content-Length:"+ 4 +"\r\n").getBytes());
out.write("\r\n".getBytes());
out.write("done".getBytes());
}
if(msg.startsWith("GET")){
String path = msg.substring(msg.indexOf("/"), msg.indexOf("HTTP")).trim();
if(path.equals("/")) out.write(response.getBytes());
else {
String fileName = path.substring(1);
fileName = URLDecoder.decode(fileName,"UTF-8");
System.out.println(fileName);
File file = new File(fileName);
if(file.exists()){
System.out.println(file.getName() + " " + file.length());
out.write("HTTP/1.1 200 OK\r\n".getBytes());
out.write("Accept-Ranges: bytes\r\n".getBytes());
out.write(("Transfer-Encoding: chunked\r\n").getBytes());
out.write("Content-Type: application/octet-stream\r\n".getBytes());
out.write(("Content-Disposition: attachment; filename=\""+file.getName()+"\"\r\n").getBytes());
out.write("\r\n".getBytes());
try{
Files.copy(Paths.get(file.getPath()) , out);
}catch(Exception e){
break;
}
}else System.out.println("file not existes");
}
}
out.flush();
os.close();
read = in.read(buffer);
}
System.err.println("closing scoket");
out.close();
in.close();
client.close();
clients.remove(client);
} catch (IOException e) {
e.printStackTrace();
}
}
}
ALL right found the bug I am not clearing the buffer hence it appears again

Download link will download the file in system download path

Error Code with fileinnfo
FileInfo File = new FileInfo(Server.MapPath("/Content/ExcelFiles/SalesTarget.xlsx"));
if (File != null)
{
int Size = Convert.ToInt32(File.Length);
string FileName = File.FullName;
int Position = FileName.LastIndexOf("\\");
FileName = FileName.Substring(Position + 1);
string test = File.GetType().ToString();
string filepath = Server.MapPath("/Content/ExcelFiles/SalesTarget.xlsx");
string ContentType = MimeMapping.GetMimeMapping(Server.MapPath("/Content/ExcelFiles/SalesTarget.xlsx"));
byte[] FileData = new byte[Size];
char[] chars = Encoding.Unicode.GetChars(FileData);
StreamReader reader = new StreamReader(filepath);
reader.Read(chars, 0, Size); // Throwing error here
Response.ContentType = ContentType;
StringBuilder SB = new StringBuilder();
SB.Append("filename=");
SB.Append(FileName);
Response.AddHeader("Content-Disposition", SB.ToString());
Response.BinaryWrite(FileData);
Response.Flush();
Response.End();
//File..Read(FileData, 0, Size);
}
Running Code with Httppostedfile Class:
HttpPostedFileBase File = Request.Files["FileToLoad"];
if (File != null)
{
int Size = File.ContentLength;
if (Size <= 0)
{
ViewData["ERROR"] = "You uploaded an empty file,please browse a valid file to upload";
return View("../Shared/Error");
}
string FileName = File.FileName;
int Position = FileName.LastIndexOf("\\");
FileName = FileName.Substring(Position + 1);
string ContentType = File.ContentType;
byte[] FileData = new byte[Size];
File.InputStream.Read(FileData, 0, Size);
theModel.AddAFile(FileName, Size, ContentType, FileData);
}
I want to download existing file from directory instead of using httppostedfile, so I am getting error while reading file data.

Send a file from server to client in GWT

I am using GWT.
I have to download a file file from server to client.
Document is in the external repository.
Client sends the id of the document through a Servlet.
On server side: Using this ID document is retrieved:
Document document = (Document)session.getObject(docId);
ContentStream contentStream = document.getContentStream();
ByteArrayInputStream inputStream = (ByteArrayInputStream) contentStream.getStream();
int c;
while ((c = inputStream.read()) != -1) {
System.out.print((char) c);
}
String mime = contentStream.getMimeType();
String name = contentStream.getFileName();
InputStream strm = contentStream.getStream();
Here I can read the document.
I want to send this to the client.
How do I make this a file and send it back to the client?
In Your Servlet:
Document document =(Document)session.getObject(docId);
ContentStream contentStream = document.getContentStream();
String name = contentStream.getFileName();
response.setHeader("Content-Type", "application/octet-stream;");
response.setHeader("Content-Disposition", "attachment;filename=\"" + name + "\"");
OutputStream os = response.getOutputStream();
InputStream is =
(ByteArrayInputStream) contentStream.getStream();
BufferedInputStream buf = new BufferedInputStream(is);
int readBytes=0;
while((readBytes=buf.read())!=-1) {
os.write(readBytes);
}
os.flush();
os.close();// *important*
return;
You can create a standard servlet (which extends HttpServlet and not RemoteServiceServlet) on server side and opportunity to submit the id as servlet parameter on client side.
Now you need after getting request create the excel file and send it to the client. Browser shows automatically popup with download dialog box.
But you should make sure that you set the right content-type response headers. This header will instruct the browser which type of file is it.
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String fileId = reguest.getParameter("fileId"); // value of file id from request
File file = CreatorExel.getFile(fileId); // your method to create file from helper class
// setting response headers
response.setHeader("Content-Type", getServletContext().getMimeType(file.getName()));
response.setHeader("Content-Length", file.length());
response.setHeader("Content-Disposition", "inline; filename=\"" + file.getName() + "\"");
BufferedInputStream input = null;
BufferedOutputStream output = null;
try {
InputStream inputStream = new FileInputStream(file);
ServletOutputStream outputStream = response.getOutputStream();
input = new BufferedInputStream(fileInput);
output = new BufferedOutputStream(outputStream);
int count;
byte[] buffer = new byte[8192]; // buffer size is 512*16
while ((count = input.read(buffer)) > 0) {
output.write(buffer, 0, count);
}
} finally {
if (output != null) {
try {
output.close();
} catch (IOException ex) {
}
}
if (input != null) {
try {
input.close();
} catch (IOException ex) {
}
}
}

Weird EOF Exception while trying to download file from GWT application

I am trying to download a file from GWT client. At server side there is a servlet which generates content of file as per request and send it back to the client.
Test Scenarios:
Scenario 1 If I hit url of servlet directly, it always give me desired result without any problems.
Scenario 2
Using GWT client on IE8,I am able to download file without any code changes. However on some other computer as soon as I try to write file content on response output stream, I get EOF exception.
org.mortbay.jetty.EofException
at org.mortbay.jetty.HttpGenerator.flush(HttpGenerator.java:760)
at org.mortbay.jetty.AbstractGenerator$Output.flush(AbstractGenerator.java:566)
at org.mortbay.jetty.HttpConnection$Output.flush(HttpConnection.java:911)
at java.io.BufferedOutputStream.flush(Unknown Source)
atXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX.doGet(ServiceDataExporterServlet.java:110)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:617)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)Creating input stream....
Code of servlet is as follows:
try
{
output = new BufferedOutputStream(response.getOutputStream(), DEFAULT_BUFFER_SIZE);
byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
int length;
int bytesWritten=0;
while ((length = data.read(buffer)) > 0) {
bytesWritten+=length;
output.write(buffer, 0, length);
}
output.flush() // At this point I am facing EOF exception.
where data is inputStream
Via means of bytesWritten variable I have confirmed that in all the three scenarios content has been written in the same way in output stream. But not sure why it is not working in some computers.
Any points will be highly appereciated.
I do something like this to download files with GWT
In the server side:
public static void sendFileToClient(String path, String filename,
int contentLen, HttpServletRequest request,
HttpServletResponse response) throws UnsupportedEncodingException
{
String ua = request.getHeader("User-Agent").toLowerCase();
boolean isIE = ((ua.indexOf("msie 6.0") != -1) || (ua
.indexOf("msie 7.0") != -1)) ? true : false;
String encName = URLEncoder.encode(filename, "UTF-8");
// Derived from Squirrel Mail and from
// http://www.jspwiki.org/wiki/BugSSLAndIENoCacheBug
if (request.isSecure())
{
response.addHeader("Pragma", "no-cache");
response.addHeader("Expires", "-1");
response.addHeader("Cache-Control", "no-cache");
}
else
{
response.addHeader("Cache-Control", "private");
response.addHeader("Pragma", "public");
}
if (isIE)
{
response.addHeader("Content-Disposition", "attachment; filename=\"" + encName + "\"");
response.addHeader("Connection", "close");
response.setContentType("application/force-download; name=\"" + encName + "\"");
}
else
{
response.addHeader("Content-Disposition", "attachment; filename=\""
+ encName + "\"");
response.setContentType("application/octet-stream; name=\""
+ encName + "\"");
if (contentLen > 0)
response.setContentLength(contentLen);
}
try
{
FileInputStream zipIn = new FileInputStream(new File(path));
ServletOutputStream out = response.getOutputStream();
response.setBufferSize(8 * 1024);
int bufSize = response.getBufferSize();
byte[] buffer = new byte[bufSize];
BufferedInputStream bis = new BufferedInputStream(zipIn, bufSize);
int count;
while ((count = bis.read(buffer, 0, bufSize)) != -1)
{
out.write(buffer, 0, count);
}
bis.close();
zipIn.close();
out.flush();
out.close();
}
catch (FileNotFoundException e)
{
System.out.println("File not found");
}
catch (IOException e)
{
System.out.println("IO error");
}
}
I have a servlet that expects for an id and then I get the related file path and I serve it to the browser with the above code.
In the client side:
public class DownloadIFrame extends Frame implements LoadHandler,
HasLoadHandlers
{
public static final String DOWNLOAD_FRAME = "__gwt_downloadFrame";
public DownloadIFrame(String url)
{
super();
setSize("0px", "0px");
setVisible(false);
RootPanel rp = RootPanel.get(DOWNLOAD_FRAME);
if (rp != null)
{
addLoadHandler(this);
rp.add(this);
setUrl(url);
}
else
openURLInNewWindow(url);
}
native void openURLInNewWindow(String url) /*-{
$wnd.open(url);
}-*/;
public HandlerRegistration addLoadHandler(LoadHandler handler)
{
return addHandler(handler, LoadEvent.getType());
}
public void onLoad(LoadEvent event)
{
}
}
In you hosted page add this Iframe
<iframe src="javascript:''" id="__gwt_downloadFrame" tabIndex='-1' style="position:absolute;width:0;height:0;border:0"></iframe>
Then to download a file put something like this:
btnDownload.addClickHandler(new ClickHandler()
{
public void onClick(ClickEvent arg0)
{
String url = GWT.getModuleBaseURL()
+ "/downloadServlet?id=[FILE_ID]";
new DownloadIFrame(url);
}
});
I hope this helps you.
Happy coding!
It happens also if the OutputStream flushes after InputStream was closed, like this:
myInputStream.close();
myOutputStream.flush();
myOutputStream.close();
it should be like:
myOutputStream.flush();
myInputStream.close();
myOutputStream.close();
Hope it helps :-)