This question already has answers here:
Using jQuery AJAX to download a binary file
(4 answers)
Closed 5 years ago.
I have a requirement to download a csv file from a Spring MVC application. I have the data which I need to include in the file. I need to create a file on the fly in the browser session and download it to the user system. I tried doing the solution as mentioned here: Downloading a file from spring controllers
I was unable to produce the csv and it is looking for a file on the server.
What I have done so far:
Client Side Call:
$.ajax({
type: "GET",
url:"${ctx}/emp/getAttendance?empId=" + emp +"&fileName=" + file,
success: function (data) {
$('#result_loading').hide();
}
});
Server Side:
String path = req.getServletContext().getRealPath("");
File file = new File(path + "/" + fileName);
file.createNewFile();
FileInputStream inputStream = new FileInputStream(file);
resp.setContentType("application/pdf");
resp.setHeader("content-disposition;","attachment;filename=\"download.pdf\"");
OutputStream outputStream = resp.getOutputStream();
IOUtils.copy(inputStream, outputStream);
outputStream.close();
I need the Ajax call to download the file. I don't see even an empty file downloaded.
Can someone help me with this on where I am doing wrong.
You can use the FileSystemResource class from the spring framework
the class exists in the location
org.springframework.core.io.FileSystemResource
Write your data onto a file (on the physical server) by creating a csv file using the java.io.File Class and then pass the value of the file object to the constructor
FileSystemResource(File file)
and return this to the browser, the browser will automatically open up a download window once the url is loaded.
Delete the file once the file system resource is initialized, and you would be as good as you never created the file.
Related
I have a database where the user doesn't has access to.
Still I can go to the database and "read" the documents with for example
var db:NotesDatabase = sessionAsSigner.getDatabase("","somedir/some.nsf");
In this database there's a pdf file I would like to open or download. I have the filename and the unid . If the user had acces to the database I could do it with
http(s)://[yourserver]/[application.nsf] /xsp/.ibmmodres/domino/OpenAttachment/ [application.nsf]/[UNID|/$File/[AttachmentName]?Open
How can I do it with sessionAsSigner without putting a $PublicAccess=1 field on the form ?
edit:
the pdf file is stored as attachment in a richtextfield
second edit
I'm trying to use the XSnippet from Naveen and made some changes
The error message I get is : 'OutStream' not found
The code I tried is :
response.reset();
response.setContentType("application/pdf");
response.setHeader("Content-Disposition", "inline; filename=" + zipFileName);
var embeddedObj:NotesEmbeddedObject = null;
var bufferInStream:java.io.BufferedInputStream = null;
var outStream:java.io.OutputStream = response.getOutputStream();
embeddedObj = downloadDocument.getAttachment(fileName);
if (embeddedObj != null) {
bufferInStream = new java.io.BufferedInputStream(embeddedObj.getInputStream());
var bufferLength = bufferInStream.available();
var data = new byte[bufferLength];
bufferInStream.read(data, 0, bufferLength); // Read the attachment data
ON THE NEXT LINE IS THE PROBLEM
OutStream.write(data); // Write attachment into pdf
bufferInStream.close();
embeddedObj.recycle();
}
downloadDocument.recycle();
outStream.flush();
outStream.close();
facesContext.responseComplete();
Create an XAgent (= XPage without rendering) which takes datebase + documentid + filename as URL parameters and delivers the file as response OutputStream.
The URL would be
http(s)://[yourserver]/download.nsf/download.xsp?db=[application.nsf]&unid=[UNID]&attname=[AttachmentName]
for an XAgent download.xsp in a database download.nsf.
The code behind the XAgent runs as sessionAsSigner and is able to read the file even the user itself has no right to access file's database.
Use Eric's blog (+ Java code) as a starting point. Replace "application/json" with "application/pdf" and stream pdf file instead of json data.
As an alternative you can adapt this XSnippet code from Thomas Adrian. Use download() together with grabFile() to write your pdf-File to OutputStream.
Instead of extracting attachment file to path and reading it from there you can stream the attachment right from document to response's OutputStream. Here is an XSnippet from Naveen Maurya as a good example.
If you can get the PDF file as a stream, you should be able to use the OutputStream of the external context's response.
Stephan Wissel has a blog posting about writing out an ODF file so you should be able to cut that up as a starting point.
http://www.wissel.net/blog/d6plinks/SHWL-8248MT
You already have the db so, you will just need to know the UNID of the document.
var doc = db.getDocumentByUNID(unid) 'unid is a supplied param
var itm:RichTextItem = doc.getFirstItem("Body") 'assuming file is in body field
Once you have the itm, you can loop round all of the embeddedObjects and get the pdf file. At this point, I don't know if you can stream it directly or if you have to detach it, but assuming you detach it, you will then use something like this.
File file = new File("path to file");
FileInputStream fileIn = new FileInputStream(file);
Don't forget to clean up the temporarily detached file
This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
how to display a pdf file in jsp using servlet
I retrieve a pdf file from my database and put it in a file like this
String str="select * from files where name='Security.pdf';";
Statement stmt2= conn.createStatement
(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE);
rs = stmt2.executeQuery(str);
while(rs.next())
{
InputStream input = rs.getBinaryStream("content");
//to create file
File f=new File("c:/pdfile.pdf");
OutputStream out=new FileOutputStream(f);
byte buf[]=new byte[1024];
int len;
while((len=input.read(buf))>0)
out.write(buf,0,len);
out.close();
input.close();
System.out.println("\nFile is created..");
}
Now this is at server end. In my client side, Whenever user clicks a link say
a href=pdf(pdf is my servlet name) in my jsp page, I should display the file retrieved from database on client's Browser.
What should I do?
Set your content-type of the response to pdf
response.setContentType("application/pdf");
Then write the pdf contents into the response object
Don't save the PDF to a file on the server, just send it back to the browser as the servlet's response. Basically, instead of that FileOutputStream, use the OutputStream that you get from calling getOutputStream() on your ServletResponse object. You'll also need to set a Content-Type header so that the browser knows it's a PDF file.
Having a servlet write to a hard-coded path like that is dangerous because several instances of the servlet can run at the same time, in different threads. (Think about what happens if two people enter your servlet's URL in their browsers at the same time.) If they're both writing to the same file at the same time, they'll end up corrupting it.
I'm coding a Spring MVC project on Eclipse. I'm stuck when coding the upload picture function. The client side using HTML5 API to read and send multipart file to server. The following code was used to save the image to server.
#RequestMapping(method = RequestMethod.POST)
public void processUpload(#RequestParam("pic") MultipartFile file) throws IOException {
// if (!result.hasErrors()) {
FileOutputStream outputStream = null;
String filePath = System.getProperty("java.io.tmpdir") + "/" + file.getOriginalFilename();
try {
outputStream = new FileOutputStream(new File(filePath));
outputStream.write(file.getInputStream().read());
outputStream.close();
} catch (Exception e) {
System.out.println("Error while saving file");
The file sent to server and get proceed but the file name is not original file name but some random string that java generated. I found that file in apache-tomcat-6.0.26\work\Catalina\localhost\ with name like this: upload__f20d9c4_1357767c999__7ffe_00000001. The file then disappear.
My question is where the file gone and how to correctly write uploaded file to some folder such as /uploads rather than save to temp folder?
I'm new hear so please correct me if I posted wrong :D
This might help :-
Change the file type to CommonsMultipartFile when you are fetching the file MultipartFile.
file.transferTo(new File("D:/"));
Let me know if this helps.
This may help as well :- http://www.codejava.net/frameworks/spring/spring-mvc-file-upload-tutorial-with-eclipse-ide
I have a Java project which is used as a component in a webapp. This java code writes an xls file in a specific folder. I want to provide a download functionality for this file which should be triggered as soon as file writing is done.
The problem is - without a server environment, how can write a download functionality?
Don't write to file in a specific folder. Just write to the HTTP response body immediately. The downloading job should just be done in the webapp's code. I assume that you're using Servlets. If you set the HTTP response Content-Disposition header to attachment, then the browser will pop a Save as dialogue. If you also set the Content-Type header, then the browser will understand what to do with it (e.g. it will then be able to ask Do you want to open it in Excel or to save? and so on).
response.setHeader("Content-Type", "application/vnd.ms-excel");
response.setHeader("Content-Disposition", "attachment;filename=\"" + filename + "\"");
// Now write xls to response.getOutputStream() instead of FileOutputStream.
If the API of that Java project is well designed, then you should have a method something like this:
public void writeXls(OutputStream output) throws IOException {
// Do your job to write xls to output. E.g. if you were using POI HSSF:
// WritableWorkbook workBook = Workbook.createWorkbook(output);
// ...
}
This way you can call it in the servlet as follows after setting the aforementioned headers:
yourClass.writeXls(response.getOutputStream());
Even more, it could easily be reused/tested in a plain vanilla Java application like follows:
yourClass.writeXls(new FileOutputStream("/path/to/foo.xls"));
This is how i do it. I show a download sql in my page.
response.setHeader("Content-Disposition", "attachment; " +
"filename=ContactPurge.sql");
response.setContentType("application/x-sql-data");
response.getWriter().write(procsql);
response.getWriter().write(sql);
response.flushBuffer();
I have one problem that is to upload file. It is working perfectly on my computer but fails when deploying to a server.
The system is to browse the file, then the system will zip it before uploading it to the server. When a client browse a file, the server will generate an error that the file is not found. Here is my code:
try {
//This is a code to read a zipfile.
String dir = request.getParameter("dirs");
System.out.println(dir);
String tmp = dir.replace( '\\', '/' );
System.out.println(tmp);
String inFilename = tmp;
// String inFilename = dir;
String outFilename = "c:/sms.zip";
//String outFilename = "/webapps/ROOT/sms.zip";
FileInputStream in = new FileInputStream( inFilename);
ZipOutputStream out = new ZipOutputStream(
new FileOutputStream(outFilename));
// Add ZIP entry to output stream.
out.putNextEntry(new ZipEntry(inFilename));
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
//End of zipping file.
//Start uploading.
SimpleFTP ftp = new SimpleFTP();
// Connect to an FTP server on port 21.
ftp.connect("xxxxx", 21, "xxx", "xxxx");
// Set binary mode.
ftp.bin();
// Change to a new working directory on the FTP server.
ftp.cwd("web");
// Upload some files.
ftp.stor(new File("sms.zip"));
ftp.disconnect();
//finish uploading
out.closeEntry();
out.close();
in.close();
response.sendRedirect("../BakMeClient/success.jsp");
}
catch (IOException e) {
System.out.println(e);
}
String dir is the location of file.
The error message is:
java.io.FileNotFoundException: D:\RELIVA\listmenu.java (The system cannot find the file specified)
Thanks for all your comments. From my observation the problem is this script is run on the server not on the client.
What I mean is let's say you browse the file for example at c:/test.txt. When you click the upload button, the form will send the path to the server and the server will find the path in its own directory and of course it will not find it.
I hope you get the idea what happened. So now: how to made it read the path at the client?
Here is definitely a problem:
// Upload some files.
ftp.stor(new File("sms.zip"));
The archive has been created at c:/sms.zip but you try to read it from the relative file location sms.zip (which is equal to ${JAVA_HOME}/sms.zip if I remember correctly The correct part is in Joachim's comment, thanks!!).
Replace these lines with
// Upload some files.
ftp.stor(new File("c:/sms.zip"));
If this doesn't help, then in addition try closing the ZipOutputStream before you send the file with FTP. There's a chance that the ZIP file has not been created yet on the file system just because the stream is still open.
There's a major misunderstanding here. You're sending local disk file system paths around instead of the actual file contents. Imagine that I am the client and I have a file at c:/passwords.txt and I give the path to you. How would you as being a server ever get its contents?
With new FileInputStream("c:/passwords.txt")? No, that is fortunately not going to happen. It will only work when both the client and server runs at physically same machine, as you have found out.
Uploading files with HTML (regardless of if it's inside a JSP file) is supposed to be done with an <input type="file"> field as follows:
<form action="upload" method="post" enctype="multipart/form-data">
<input type="file" name="file">
<input type="submit">
</form>
This way the file will be sent in the request body. As the standard Servlet API versions up to with 2.5 doesn't support mulipart/form-data requests, you need to parse the request yourself. The best way is to use Apache Commons FileUpload for this. Follow the link and read both the User Guide and Frequently Asked Questions for code examples and tips&tricks. When you're already on Servlet 3.0, then you can just use the Servlet API provided HttpServletRequest#getParts() for this. You can find here an article with code examples about that.
If you actually want to upload a complete folder with files to the server side and you don't want to use multiple <input type="file"> fields for this, then you'll need Applet or SWF for this, because this isn't possible with plain vanilla HTML. In the server side you can parse the request just the same way.
I think, if it is working in your system and not in server, there must be problem with server settings.
Or you can check following things
Need to check path you are working on.
Before uploading, try to list the files in that directory, once you generate ZIP file.
Check for permissions.
Your outFilename must be found in the web. Like: "http://www.sample.com/sms.zip" or the likes..