WMV file downloading in jsp - java

I have a jsp written in which i am downloading certain files... they are pdf, zip, ppt and wmv. All the file types works except wmv. I couldnt figure out problem. When i play wmv file i get following error.
Windows Media Player cannot play the file. The Player might not support the file type or might not support the codec that was used to compress the file.
In my jps i have written code as following
response.setContentType("video/x-ms-wmv");
response.setCharacterEncoding("utf-8");
response.setHeader("Content-disposition", "attachment; filename=123.wmv;");
String fileName = "/logs/164266828.wmv";
FileInputStream input = new FileInputStream(fileName);
BufferedInputStream buf = new BufferedInputStream(input);
int readBytes = 0;
ServletOutputStream myOut = response.getOutputStream( );
while((readBytes = buf.read( )) != -1)
myOut.write(readBytes);
Any inputs or modifications would be of great help !!!

Do not use JSP to stream binary data. JSP may have corrupted it with template text (whitespace and so on outside those <% %> things). Move this code to the doGet() method of a servlet class and invoke the servlet instead of JSP.
Unrelated to the concrete problem, those files seems static files. You don't necessarily need a servlet for this if you have full control over your server. In case of for example Tomcat, you could add the folder with the static files as another <Context> to the server.xml file.
See also:
Reliable data serving
Simplest way to serve static data from outside the application server in a Java web application

Related

Read and Append data to the File from a Blob URL path before download

This is my first hands on using Java Spring boot in a project, as I have mostly used C# and I have a requirement of reading a file from a blob URL path and appending some string data(like a key) to the same file in the stream before my API downloads the file.
Here are the ways that I have tried to do it:
FileOutputStream/InputStream: This throws a FileNotfoundException as it is not able to resolve the blob path.
URLConnection: This got me somewhere and I was able to download the file successfully but when I tried to write/append some value to the file before I download, I failed.
the code I have been doing.
//EXTERNAL_FILE_PATH is the azure storage path ending with for e.g. *.txt
URL urlPath = new URL(EXTERNAL_FILE_PATH);
URLConnection connection = urlPath.openConnection();
connection.setDoOutput(true); //I am doing this as I need to append some data and the docs mention to set this flag to true.
OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());
out.write("I have added this");
out.close();
//this is where the issues exists as the error throws saying it cannot read data as the output is set to true and it can only write and no read operation is allowed. So, I get a 405, Method not allowed...
inputStream = connection.getInputStream();
I am not sure if the framework allows me to modify some file in the URL path and read it simultaneously and download the same.
Please help me in understanding if they is a better way possible here.
From logical point of view you are not appending data to the file from URL. You need to create new file, write some data and after that append content from file from URL. Algorithm could look like below:
Create new File on the disk, maybe in TMP folder.
Write some data to the file.
Download file from the URL and append it to file on the disk.
Some good articles from which you can start:
Download a File From an URL in Java
How to download and save a file from Internet using Java?
How to append text to an existing file in Java
How to write data with FileOutputStream without losing old data?

Spring web application save file to server

I build a web application.
I would like to read files from server, then generate PDF file ( with itText) then save it to the server.
I don't know how to locate the files from the server then save the file to the server.
I read from my PC and write data to my PC perfectly.
The above code works properly but just on my computer not at server.
String jspPath = "C:\\Users\\dave\\Desktop\\eclipse\\project\\";
String fileName = "CV.txt";
InputStreamReader ir = new InputStreamReader(new FileInputStream(jspPath+filename), "UTF-8");
// Then generate the PDF with iText
//and
FileOutputStream fs = new FileOutputStream(jspPath+"generated.pdf");
PdfWriter pdfWriter = new PdfWriter(fs);
PdfDocument pdfdoc = new PdfDocument(pdfWriter);
JSP path references to my folder not the link with the generated pdf.
I would like :
put CV.txt to the server and read it.
Generate pdf ( it will work).
Save the generated PDF to server
A link to the generated PDF which i can download.
Thanks in Advance
Here are few things which might help you.
You can use FormData to pass text file from Frontend to Backend.
Use ajax post call to pass data.
you will have entire file on backend in the RequestContext parameter as FileItem object. you can start reading file using InputStreamReader.
than convert it into pdf file.
you can save pdf file to java temporary directory
String temporaryDir = System.getProperty("java.io.tmpdir");
this will return path for java temporary directory and you can delete this pdf file later
you will have to create ResponseBuilder with content-type='application/pdf' to download as a pdf file and return it to the UI. read this post
Hope this information helps you to solve your issue!

How do I "import" a HTML file from a shared drive into a JSP from my war file?

Preface: I am an inexperienced java programmer handed one of his first assignments. If I do not ask the question correctly or do not give enough detail, please let me know.
I am trying to import a HTML page that is saved on my C drive. I am trying to import it to the content portion (div id="content") of a JSP file that exists in a war file. I have already figured out that I can not use jsp:include, #include, #include file because the file exists outside the war file. I also figured out that c:import and iFrame do not work.
My goal is to make the contents of the html file that is saved in on my c drive appear in the contents of the jsp (visible on the web page).
Am I on the right track with this <% File f = new File("c:\\temp\\filename.html").......%>
I have searched stackoverflow and the only topic that came close was "How to Include a file outside the application (war) using jsp include." It did not really get me where I needed to go. Maybe the answer is right in front of me but I couldnt see it.
JSP/JSTL does not offer tags which support this. You'd need to do it using pure Java. You just have to write it to the response yourself.
Here's one of the simplest ways:
<%
Reader reader = new FileReader("c:/path/to/external/file.html");
try {
for (int i = 0; (i = reader.read()) != -1;) {
out.write(i);
}
} finally {
try { reader.close(); } catch (IOException ignore) {}
}
%>
You could wrap it in a custom tag to keep your JSP free of scriptlet clutter, or you could read it into a String in a servlet and pass it to JSP EL scope.
Do you want clients to see the contents of filename.html located on your server? If so, why don't you just get it inside your project/war?
Or do you want clients to see the contents of a filename.html they have on their computers? If so, you might be able to just add an iframe with that source... but you'll run into many security-related problems, since browsers won't ordinarily let you do that.
Try
<% File f = new File("c:\\temp\\filename.html");
BufferedReader in = new BufferedReader(new FileReader(f));
while (in.readLine() != null) {
out.println(blah blah blah);
}
in.close();
%>
reading the File and Printing it to the JSP should work,
My suggestion is to use http form upload in your jsp application. In that case your file can be in any place that is accesible in your filesystem instead of hardcoding it to be in a certain place. Usage http://commons.apache.org/fileupload/using.html
Good tutorial on http://www.servletworld.com/servlet-tutorials/servlet-file-upload-example.html
Some useful hints can also be found in the video, http://www.youtube.com/watch?v=BLamJlRg9Ws

How to upload a directory via Grails or Java?

What is the best way to upload a directory in grails ?
I try this code :
def upload = {
if(request.method == 'POST') {
Iterator itr = request.getFileNames();
while(itr.hasNext()) {
MultipartFile file = request.getFile(itr.next());
File destination = new File(file.getOriginalFilename())
if (!file.isEmpty()) {
file.transferTo(destination)
// success
}
else
{
// failure
}
}
response.sendError(200,'Done');
}
}
Unfortunately, I can only upload file by file.
I would like to define my directory, and upload all files directly.
Any ideas ?
There is one major misconception here. The code which you posted will only work if both the server and the client runs at physically the same machine (which won't occur in real world) and if you're using the MSIE browser which has the misbehaviour to send the full path along the filename.
You should in fact get the contents of the uploaded file as an InputStream and write it to any OutputStream the usual Java IO way. The filename can be used to create a file with the same name at the server side, but you'll ensure that you strip the incorrectly by MSIE sent path from the filename.
As to your actual functional requirement, HTML doesn't provide facilities to upload complete directories or multiple files by a single <input type="file"> element. You'll need to create a client application which is capable of this and serve this from your webpage, like a Java Applet using Swing JFileChooser. There exist 3rd party solutions for this, like JumpLoader.

JSP: I am doing an application in which i have to download ppt file

I am working on an application wherein I have to download a PPT file using a JSP page. I am using the following code, but it's not working.
<% try {
String filename = "file/abc.ppt";
// set the http content type to "APPLICATION/OCTET-STREAM
response.setContentType("APPLICATION/OCTET-STREAM");
// initialize the http content-disposition header to
// indicate a file attachment with the default filename
// "myFile.txt"
String disHeader = "Attachment Filename=\"abc.ppt\"";
response.setHeader("Content-Disposition", disHeader);
// transfer the file byte-by-byte to the response object
File fileToDownload = new File(filename);
FileInputStream fileInputStream = new
FileInputStream(fileToDownload);
int i;
while ((i=fileInputStream.read())!=-1)
{
out.write(i);
}
fileInputStream.close();
out.close();
}catch(Exception e) // file IO errors
{
e.printStackTrace();
}
%>
Can anybody solve this problem?
Not only the Content-Disposition header is incorrect, but you're incorrectly using JSP instead of a Servlet for this particular task.
JSP is a view technology. Everything outside the scriptlets <% %> will be printed to the response, including whitespace characters such as newlines. It would surely corrupt binary files.
You could trim the whitespace in the JSP file, but scriptlets are discouraged since a decade and nowadays considered bad practice. Raw Java code belongs in Java classes, not in JSP files. The real solution is to use a HttpServlet for this.
Create a class which extends HttpServlet, implement the doGet() method, move the Java code from the JSP file into this method, map this servlet on a certain url-pattern and your problem should disappear. You can find here a basic example of such a servlet.
Off the top there should be a semicolon in the Content-Disposition header ("attachment*;* filename ...)
You should also probably do a response.reset() before starting to set headers and stream. Internet Explorer has really strange rules about streaming files from secure sockets and won't work right if you don't clear the caching headers.

Categories