Spring MVC Ajax upload PDF file for preview - java

I'm trying to get a PDF File preview with Js plugin PDFObject.
In order to do this I'm sending the PdfFile to my Server which save it in a specific folder. This step works perfectly fine I'm getting the pdf in the right folder.
But when I send my Pdf as an byte array in the ajax response and try to open it in a new tab (or in the PDFObject tag) I'm getting a loading failure of the file.
Client:
$.ajax({
method: "POST",
url: "documents/preview",
processData: false,
contentType: false,
data: formData,
success : function(file) {
window.open("data:application/pdf," + file);
PDFObject.embed("data:application/pdf," + file, "#pdf-preview");
},
error : function(err) {
alert("Error : " + err);
}
})
Server:
final File file = new File("path/to/pdf/file.pdf");
response.setContentType("application/pdf");
response.setContentLength(Long.valueOf(file.length()).intValue());
response.setHeader("Content-Disposition", "attachment; filename=" + file.getOriginalFilename());
fileInputStream = new FileInputStream(fichier);
final byte[] data = IOUtils.toByteArray(fileInputStream);
response.getOutputStream().write(data);
Unless I escape the data like this :
window.open("data:application/pdf," + escape(file));
PDFObject.embed("data:application/pdf," + escape(file), "#pdf-preview");
Then the pdf load in the correct format and with the correct ammount of pages, the only thing being that their is no data in it, all pages are blank.
When I inspect the "file" variable in chrome console I'm getting weird stuff in each stream part of the pdf file like this :
>file
"%PDF-1.3
%�����������
4 0 obj
<< /Length 5 0 R /Filter /FlateDecode >>
stream
x�\�r9r��S��nFk����|�=Z�7�ݙ>x�#�-
7(���~_L�a����>�2�(���ٜqHQh

Related

Open a pdf file using javax.ws and angular

I am trying to open a PDF file, saved in the server, using a Java Restful service and angularjs.
My code for the service in Java is:
#GET
#Path("/getPDF")
#Produces("application/pdf")
public Response getPDF() throws FileNotFoundException {
File file = new File("/path/to/file.pdf");
FileInputStream fileInputStream;
fileInputStream = new FileInputStream(file);
long contentLength = file.length();
ResponseBuilder responseBuilder = Response.ok((Object) fileInputStream);
responseBuilder.type("application/pdf");
responseBuilder.header("Content-Disposition", "inline; filename=file.pdf");
responseBuilder.header("Content-Length", contentLength);
responseBuilder.header("charset", "utf-8");
return responseBuilder.build();
}
Once the Response is returned I handle the request with angularjs:
MyJavaService.getPDF().success(function(data){
var file = new Blob([data], {type: 'application/pdf'});
var fileURL = URL.createObjectURL(file);
$window.open(fileURL);
});
The result is that a new window opens, with the same number of pages like the PDF file (correct), but the content is not displayed and all the pages are white (not correct).
Does anyone have any clue of what am I doing wrong?
I'm assuming you're using a $http.get() call.
You probably having something along the lines of:
$http.get(<URL>, {params: <stuff>})
You need to tell angular that the responseType is an arrayBuffer like so:
$http.get(<URL>, {responseType: 'arraybuffer', params: <stuff>})
Don't hesitate to tell me my assumptions are incorrect.
p.s.: try to avoid using .success() and instead use .then(). The former is deprecated 1.4+ and completely removed in 1.6+

Large file does not download with jsp

I am sending an AJAX POST request from the script inside JSP.
Inside controller i am reading the file from the location and return the byte Array.
fileInputStreamReader = new FileInputStream(file);
byte[] bytes = new byte[(int) file.length()];
fileInputStreamReader.read(bytes);
filedata = Base64.getEncoder().encode(bytes);
response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
response.setContentLength((int) file.length());
fileInputStreamReader.close();
Then on the front end i am crating an invisible link and downloading the file.
$.ajax({
url : url,
type : 'POST',
data : nodedata,
beforeSend : function(jqXHR, settings) {
setCsrfHeader(jqXHR);
},
success : function(data) {
hideLoader();
/* window.open("data:"+contentType+";base64, " + data); */
var uri = 'data:'+contentType+';base64,' + data;
var downloadLink = document.createElement("a");
downloadLink.href = uri;
downloadLink.download =atcName ;
document.body.appendChild(downloadLink);
downloadLink.click();
$("#Success").html("File download successful");
$("#error").hide();
$("#Success").show();
document.body.removeChild(downloadLink);
},
error : function(e) {
hideLoader();
$("#error").html(ERROR_SERVER_RESPONSE);
$("#Success").hide();
$("#error").show();
alert(ERROR_SERVER_RESPONSE);
}
});
The problem is only with large file size >~50mb. What should I do?
I might be wrong but I suggest to check if there is no cache issue because a timeout should trigger an error callback.
You should add the aparameter cache : false, in your request or, better IMHO, you can prevent all futher Ajaxs call from being cached, regardless of which jQuery method you use(ajax, get...).
$.ajaxSetup({ cache: false });

Upload file stop with Unexpected EOF read on the socket Exception

Sometime when I try to upload a file on my remote vps i get this exception (the upload proccess stop in 60%)
06-Jan-2016 11:59:36.801 SEVERE [http-nio-54000-exec-9] org.apache.catalina.core.StandardWrapperValve.invoke Servlet.service() for servlet [mvc-dispatcher] in context with path [] threw exception [Request processing failed;
nested exception is org.springframework.web.multipart.MultipartException: Could not parse multipart servlet request;
nested exception is org.apache.commons.fileupload.FileUploadBase$IOFileUploadException: Processing of multipart/form-data request failed. Unexpected EOF read on the socket]
with root cause
java.io.EOFException: Unexpected EOF read on the socket
and in Google Chrome the connextion is lost like the server is down, i get ERR_CONNECTION_ABORTED
i upload file like this in spring mvc
public void save_file(MultipartFile upfile , String path){
try {
File fichier = new File( path ) ;
byte[] bytes = upfile.getBytes();
BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream( fichier ));
stream.write(bytes);
stream.close();
System.out.println( "You successfully uploaded " + upfile.getOriginalFilename() + "!" );
} catch (Exception e) {
System.out.println( "You failed to upload " + upfile.getOriginalFilename() + " => " + e.getMessage() ); ;
}
}
my controller :
#RequestMapping(value = "/administration/upload", method = RequestMethod.POST)
public String Upload_AO_journal(
#ModelAttribute UploadForm uploadForm,
Model map , HttpServletRequest request, HttpSession session ) throws ParseException, UnsupportedEncodingException {
my bean
public class UploadForm {
...
public MultipartFile scan;
So how can solve this problem ?
Have you tried stream?
Jsp code:
<form method="POST" onsubmit="" ACTION="url?${_csrf.parameterName}=${_csrf.token}" ENCTYPE="multipart/form-data">
Controller:
#RequestMapping(
value = "url", method = RequestMethod.POST
)
public void uploadFile(
#RequestParam("file") MultipartFile file
) throws IOException {
InputStream input = upfile.getInputStream();
Path path = Paths.get(path);//check path
OutputStream output = Files.newOutputStream(path);
IOUtils.copy(in, out); //org.apache.commons.io.IOUtils or you can create IOUtils.copy
}
All that worked for me with spring 4.0 and spring security.
Secondly, you should check if the http connection is timeout. Chrome does not support that configuration. So you can use firefox and follow here http://morgb.blogspot.com.es/2014/05/firefox-29-and-http-response-timeout.html.
Not sure about the getBytes() method on the upfile. A more suitable approach would be to use the InputStream which will manage any size file and will buffer when necessary. Something like:
public void save_file(MultipartFile upfile , String path){
try {
File fichier = new File( path ) ;
BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream( fichier ));
InputStream is = upfile.getInputStream();
byte [] bytes = new byte[1024];
int sizeRead;
while ((sizeRead = is.read(bytes,0, 1024)) > 0) {
stream.write(bytes, 0, sizeRead);
}
stream.flush();
stream.close();
System.out.println( "You successfully uploaded " + upfile.getOriginalFilename() + "!" );
} catch (Exception e) {
System.out.println( "You failed to upload " + upfile.getOriginalFilename() + " => " + e.getMessage() ); ;
}
}
This issue appears because you close stream until stream write whole data.
Wrong way:
stream.write(bytes);
stream.close();
Right way:
try (BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(fichier)))
{
stream.write(data);
}
You should close your stream after whole data is written.
I had similar issues and problem is when you are uploading file you are using Multipart Form POST Request. You can read about MIME .
MIME-Version: 1.0
Content-Type: multipart/mixed; boundary=frontier
This is a message with multiple parts in MIME format.
--frontier
Content-Type: text/plain
This is the body of the message.
--frontier
Content-Type: application/octet-stream
Content-Transfer-Encoding: base64
PGh0bWw+CiAgPGhlYWQ+CiAgPC9oZWFkPgogIDxib2R5PgogICAgPHA+VGhpcyBpcyB0aGUg
Ym9keSBvZiB0aGUgbWVzc2FnZS48L3A+CiAgPC9ib2R5Pgo8L2h0bWw+Cg==
--frontier--
Basically issue I had was that multipart from request has meta information part, text part and actual file encoded I believe in base64. Each of this parts are split by boundary. If you don't set up this boundary (in example above it's called "frontier") correctly server starts reading the file but doesn't know where it ends until it reaches EOF and returns error about unexpected EOF because it didn't found required boundaries.
Problem with your code is that you are writing file into ByteOutputStream which is suitable when returning file from server to the user not other way around. Server is expecting this Multipart request with some standard predefined formatting. Use Apache Commons HttpClient library that does all this request formating and boundary setting for you. If you use Maven then this link.
File f = new File("/path/fileToUpload.txt");
PostMethod filePost = new PostMethod("http://host/some_path");
Part[] parts = {
new StringPart("param_name", "value"),
new FilePart(f.getName(), f)
};
filePost.setRequestEntity(
new MultipartRequestEntity(parts, filePost.getParams())
);
HttpClient client = new HttpClient();
int status = client.executeMethod(filePost);
Disclaimer: code is not mine it's example from Apache website for multipart request
I got the same error when I didn't properly set the path where the file is going to be placed.
The fix was to change it like this:
factoryMaster.setCertificateFile("E:\\Project Workspace\\Live Projects\\fileStore\\Factory Master\\"+factoryMasterBean.getFile().getOriginalFilename());
and use throws exception in controller:
public #ResponseBody ResponseEntity<FactoryMaster> saveFactoryMaster(#ModelAttribute("factoryMasterBean") FactoryMasterBean factoryMasterBean,FactoryMaster factoryMaster) throws IllegalStateException, IOException {...............}
and make sure do not send any file with the same name which already exists.

http response getting printed in browser if "Content-type" and "content-disposition" are set after writing in http "response" outputstream

I have a use-case where I have to set "Content-type" and "content-disposition" after writing in http response outputstream instead of downloading as a file. Following sample code depicts the case :-
#Context
HttpServletResponse response;
#GET
#Produces(MediaType.TEXT_PLAIN)
public String downloadFile() throws IOException {
File file = new File("/var/tmp/input.txt");
FileInputStream fs = new FileInputStream(file);
copyStream(fs, response.getOutputStream());
response.setContentType("text/csv");
response.setHeader("Content-Disposition","attachment;filename=\"" + "ts.csv" + "\"");
return "";
}
When I give a small input (input.txt file), my browser gives me option to download it but when the input is large, it prints the file content directly in the browser tab.
Any pointers what I can do such that it gives a file downoad option for large input as well?
As per documentation at ServletResponse.setContentType:
Sets the content type of the response being sent to the client, if the response has not been committed yet.
And, as per documentation at ServletResponse.getWriter:
Returns a PrintWriter object that can send character text to the client.
In your coding, you are writing content to the response object before setting the content-type.
You should have not written into the response output stream, for your custom content type to work.
Change your code:
copyStream(fs, response.getOutputStream());
response.setContentType( "text/csv" );
response.setHeader( "Content-Disposition",
"attachment;filename=\"" + "ts.csv" + "\"" );
To:
response.setContentType( "text/csv" );
response.setHeader( "Content-Disposition",
"attachment;filename=\"" + "ts.csv" + "\"" );
copyStream(fs, response.getOutputStream());

ajax response as pdf, how to show it?

I have a web service that generate a pdf. In my GAE application I have a button, when i click i use an ajax's function.
$('#test').click(function(){
$.ajax({
url: 'provaws.do',
type: 'get',
dataType: 'html',
success : function(data) {
}
});
});
this is the method in java that's call ws, using UrlFetch:
#RequestMapping(method = RequestMethod.GET, value = PROVAWS_URL)
public void prova(HttpServletRequest httpRequest, HttpServletResponse httpResponse, HttpSession httpSession) throws IOException{
try {
URL url = new URL("http://XXXXX/sap/bc/zcl_getpdf/vbeln/yyyyyy");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestProperty("Authorization","Basic " + Base64.encodeBase64String(("username:password").getBytes()));
connection.setConnectTimeout(60000);
if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
// OK
ByteArrayOutputStream bais = new ByteArrayOutputStream();
InputStream is = null;
try {
is = connection.getInputStream();
byte[] byteChunk = new byte[4096];
int n;
while ( (n = is.read(byteChunk)) > 0 ) {
bais.write(byteChunk, 0, n);
}
}
catch (IOException e) {
}
finally {
if (is != null) { is.close(); }
}
httpResponse.setContentType("application/pdf");
httpResponse.setHeader("content-disposition","attachment; filename=yyyyy.pdf");
httpResponse.getOutputStream().write(bais.toString().getBytes("UTF-8"));
httpResponse.getOutputStream().flush();
}
....
}
With Firebug i see the repsonse:
%PDF-1.3
%âãÏÓ
2 0 obj
<<
/Type /FontDescriptor
/Ascent 720
/CapHeight 660
/Descent -270
/Flags 32
/FontBBox [-177 -269 1123 866]
/FontName /Helvetica-Bold
/ItalicAngle 0
....
What i need to set in ajax's function to show the pdf?
Thanks in advance
I don't know Java well, but in my understanding your mechanism may not be right.
Here are my corrections:
Instead of sending files in stream, the server-side code(JAVA) should generate the pdf at backend, put the file in file system, and then return the URI of file to Ajax response.
For Ajax code, it get the url from server, then show the new url in DOM. Then user can follow this link to read/download PDF.
Side note:
I checked further that there are methods for streaming data by Ajax, though jQuery's ajax() can't handle that. But I think for a PDF file rendering, streaming is overkill.
Refs: jquery ajax, read the stream incrementally?, http://ajaxpatterns.org/HTTP_Streaming#In_A_Blink*

Categories

Resources