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 });
Related
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��nFk����|�=Z�7�ݙ>x�#�-
7(���~_L�a����>�2�(���ٜqHQh
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.
I know there are a lot of StackOverflow questions about this already, but I've searched through as many as I could find and have yet to get my code working, so I am finally posting my own question.
My goal is to save an image that is on an HTML5 <canvas> in my webpage to a file on my server. I was hoping to accomplish this using a Java servlet.
My JavasScript grabs the canvas image data like this:
var canvas = document.getElementById("screenshotCanvas");
var context = canvas.getContext("2d");
var imageDataURL = canvas.toDataURL('image/png');
// I'm not if I need to do this, I've tried several different ways to no avail
//imageDataURL = imageDataURL.replace("image/png", "image/octet-stream");
//imageDataURL = imageDataURL.replace(/^data:image\/(png|jpeg);base64,/,"");
$.ajax({
url: screenshotCreateUrl,
type: "POST",
data: { imgBase64: imageDataURL },
error: function(jqXHR, textStatus, errorThrown) {
// Handle errors
},
success: function(data, textStatus, jqXHR) {
// Do some stuff
}
});
My Java servlet tries to save the image like so:
try {
HttpServletRequestWrapper wrappedRequest = new HttpServletRequestWrapper(request);
HttpServletRequestWrapper requestWithWrapper = (HttpServletRequestWrapper) wrappedRequest.getRequest();
byte[] contentData = requestWithWrapper.getContentData();
byte[] decodedData = Base64.decodeBase64(contentData);
FileOutputStream fos = new FileOutputStream("testOutput.png");
fos.write(decodedData);
fos.close();
} catch(Exception e) {
// Handle exceptions
}
The servlet successfully writes out an image file, but it does not open properly and does not contain all the image data in it. My Javascript successfully grabs the <canvas> image data, which looks like this:
data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAASwAAACWCAYAAABkW7XSAAAgAElEQVR4nJTa51NcaZ7ge+QBIZBAwgoEkvDeJt577733njRk4r3PhDRAJkkmiTdCXqWqUlVXtZl209OzvWN27t17/5rvvoCu7t6ZmN158YnfcyJOnIjz4vnGEyeOWdRmAP+RaI3fT2I0PiTtBJF9KKD8TTKVb5IpPosl+zCMdFMgKQY/otTPCFl3IljhSPiWB5E7XkToPAnVexNq8CVyP5Cwg0CCDwII2vfHx+TDC6MXz3df8mznGc7bTthu2PJwxRrrufvcnzbn4bQFjnNWuK3a4r3hQrDmBSGbLwlRvyR0w5OQ9ZeErHsRsuFLyIYvQeu+BCh88Zf74K/wxU8ZgL8qEH9VEAHq0L8RqAkjeCuCsO1IwrVRhGujCNNdCdVFEayNJEQXdUUfTYg+mmC9AH99BL47YfjuhOK7G4KvIRhfQzDee4F47QXibQrCe98f730/vPf98N3zw9/kT+B+IG . . . [and so on]
Any ideas what I am missing here? I feel like i am making some tiny mistake that I just can't spot.
Had the same task and was able to make it work (without jQuery and with the help of maclema's reply), by using multipart/form-data content type:
var xhr = new XMLHttpRequest();
xhr.open("post", "AddressOfYourServlet", false);
var boundary = Math.random().toString().substr(2);
xhr.setRequestHeader("content-type",
"multipart/form-data; charset=utf-8; boundary=" + boundary);
var multipart = "--" + boundary + "\r\n" +
"Content-Disposition: form-data; name=myImg\r\n" +
"Content-type: image/png\r\n\r\n" +
canvas.toDataURL("image/png") + "\r\n" +
"--" + boundary + "--\r\n";
xhr.send(multipart);
To go asynchronously or if you have more parts to send (e.g. multiple images) or if you want to work with the response, see How to send multipart/form-data form content by ajax (no jquery)?
Your servlet's doPost method would look something like:
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Part part = request.getPart("myImg");
BufferedReader br = new BufferedReader(new InputStreamReader(part.getInputStream(),
Charset.forName("utf-8")));
String sImg = br.readLine();
sImg = sImg.substring("data:image/png;base64,".length());
byte[] bImg64 = sImg.getBytes();
byte[] bImg = Base64.decodeBase64(bImg64); // apache-commons-codec
FileOutputStream fos = new FileOutputStream("img.png");
fos.write(bImg);
}
Hope this helps.
You want to get the post parameter and not the content data of the request. As well you will also need to strip the encoding information.
Try this:
try {
HttpServletRequestWrapper wrappedRequest = new HttpServletRequestWrapper(request);
HttpServletRequestWrapper requestWithWrapper = (HttpServletRequestWrapper) wrappedRequest.getRequest();
String imageString = wrappedRequest.getParameter("imgBase64");
imageString = imageString.substring("data:image/png;base64,".length);
byte[] contentData = imageString.getBytes();
byte[] decodedData = Base64.decodeBase64( contentData );
FileOutputStream fos = new FileOutputStream("testOutput.png");
fos.write(decodedData);
fos.close();
} catch(Exception e) {
// Handle exceptions
e.printStackTrace();
}
How to provide large files for download through spring controller ? I followed few discussions on similar topic :
Downloading a file from spring controllers
but those solutions fails for large files ~ 300mb - 600mb.
I am getting OutOfMemoryException on the last line :
#RequestMapping(value = "/file/{dummyparam}.pdf", method = RequestMethod.GET, produces=MediaType.APPLICATION_OCTET_STREAM_VALUE)
public #ResponseBody byte[] getFile(#PathVariable("dummyparam") String dummyparam, HttpServletResponse response) {
.
.
InputStream is = new FileInputStream(resultFile);
response.setHeader("Content-Disposition", "attachment; filename=\"dummyname " + dummyparam + ".pdf\"");
.
.
return IOUtils.toByteArray(is);
My (naive) assumption was that IOUtils will handle even large files but this is not obviously happening. Is there any way how to split file into chunks as download is in progress ? Files are usually around 300 - 600mb large. Max number of concurrent downloads is estimated to 10.
Easy way would be to link files as static content in the webserver directory but we would like to try do it in within our Spring app.
It is because you are reading the entire file into memory, use a buffered read and write instead.
#RequestMapping(value = "/file/{dummyparam}.pdf", method = RequestMethod.GET, produces=MediaType.APPLICATION_OCTET_STREAM_VALUE)
public void getFile(#PathVariable("dummyparam") String dummyparam, HttpServletResponse response) {
InputStream is = new FileInputStream(resultFile);
response.setHeader("Content-Disposition", "attachment; filename=\"dummyname " + dummyparam + ".pdf\"");
int read=0;
byte[] bytes = new byte[BYTES_DOWNLOAD];
OutputStream os = response.getOutputStream();
while((read = is.read(bytes))!= -1){
os.write(bytes, 0, read);
}
os.flush();
os.close();
}
For Spring , Need use InputStreamResource class in ResponseEntity .
Demo Code :
MediaType mediaType = MediaTypeUtils.getMediaTypeForFileName(this.servletContext, fileName);
System.out.println("fileName: " + fileName);
System.out.println("mediaType: " + mediaType);
File file = new File(DIRECTORY + "/" + fileName);
InputStreamResource resource = new InputStreamResource(new FileInputStream(file));
return ResponseEntity.ok()
// Content-Disposition
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=" + file.getName())
// Content-Type
.contentType(mediaType)
// Contet-Length
.contentLength(file.length()) //
.body(resource);
}
Ref Link : https://o7planning.org/en/11765/spring-boot-file-download-example
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*