in my application, users can edit an ODF file via WebODF (http://webodf.org/). On save, i want to send the edited file to a servlet, have it convert to PDF via ODFDOM (http://code.google.com/p/xdocreport/wiki/ODFDOMConverterPDFViaIText) and open in a new window.
Currently i am trying to do this via AJAX. Everything works fine up to the point where i try to open the received PDF file.
My Javascript:
function showPDF(pServletUrl)
{
var successCallback = function(pData)
{
var mimetype = "application/vnd.oasis.opendocument.text";
var blob = new Blob([pData.buffer], {type: mimetype});
var formData = new FormData();
formData.append("file", blob, "test.odt");
jQuery.ajax({
type: "POST",
url: pServletUrl,
async: false,
data: formData,
processData: false,
contentType: false,
success: function(pSuccessData)
{
window.open(pSuccessData);
},
error: function(pErrorData)
{
console.log(pErrorData);
}
});
}
var errorCallback = function(data)
{
console.log(error);
}
_canvas.odfContainer().createByteArray(successCallback, errorCallback);
}
My servlet:
public void handleRequest(HttpServletRequest pRequest, HttpServletResponse pResponse) throws ServletException, IOException
{
BufferedInputStream tBufferedInput = null;
BufferedOutputStream tBufferedOutput = null;
try
{
List<FileItem> tItems = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(pRequest);
for (FileItem tItem : tItems)
{
if (!tItem.isFormField())
{
String tFieldname = tItem.getFieldName();
String tFilename = FilenameUtils.getName(tItem.getName());
InputStream tFilecontent = tItem.getInputStream();
if("file".equals(tFieldname))
{
tBufferedInput = new BufferedInputStream(tFilecontent);
pResponse.reset();
pResponse.setHeader("Content-Type", "application/pdf");
pResponse.setHeader("Content-Disposition", "inline; filename=\"" + "test.pdf" + "\"");
tBufferedOutput = new BufferedOutputStream(pResponse.getOutputStream(), 10240);
this.getOdtAsPdf(tBufferedInput, tBufferedOutput);
tBufferedOutput.flush();
}
}
}
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
try
{
tBufferedInput.close();
tBufferedOutput.close();
}
catch(Exception e)
{
}
}
}
private void getOdtAsPdf(InputStream pInputStream, OutputStream pOutputStream) throws Exception
{
OdfDocument tOdfDocument = OdfDocument.loadDocument(pInputStream);
PdfOptions tPdfOptions = PdfOptions.create();
PdfConverter.getInstance().convert(tOdfDocument, pOutputStream, tPdfOptions);
}
It seems like Javascript wants to parse the recieved PDF file as a URL and (obviously) fails doing so. Is there a way to just open the file in a new window or do i have to find another way to do this?
You can't open the file using Ajax. This is a security restriction fo javascript. You have a few workarounds:
use a plugin which gives a Ajax type experience but opens a file in a new window.more details here
have a form which is submitted to a new window. <form target=_blank /> this will cause a new window to open thus not changing the contents of your current page.
Another option (not so neat) is to store the file in session and in the response of your AJAX, pass the id. Then using Javascript make a call using window.open('downloadurl?id') which will send the response of your PDF file.
You can make use an embed tag to display your blob after you make an ajax call.
Use createObjectUrl method to get url from blob and then display your pdf.
Related
I am trying to download csv file and wanted to upload that same csv file into my server location path using Spring MVC and through Ajax Post request on executing my application.
From the below code, I can able to download my csv file on running my application, but it is not uploading into my server location path at the same time or simultaneously on executing of the application, I am not sure why it is not uploading. Please help me to upload my file at my given path. Thanks !
js:
function download_csv(csv, filename) {
//filename = test.csv
//csv = "testname,testid
hello,10"
var csvFile;
var downloadLink;
// CSV FILE
csvFile = new Blob([csv], {type: "text/csv"}); //[object Blob]
// Download link
downloadLink = document.createElement("a");
// File name
downloadLink.download = filename;
var formData = new FormData(csvFile);
console.log(formData);//FormData {}
$.ajax({
url: "/uploadFile",
type: "POST",
//data: filename,
// data: new FormData(csvFile),
data: formData,
// enctype: 'multipart/form-data',
processData: false,
contentType: false,
cache: false,
success: function (data) {
// Handle upload success
$("#upload-file-message").text("File succesfully uploaded");
},
error: function (errordata) {
console.log("error: "+errordata);//[object Object]
console.log("error data: "+JSON.stringify(errordata));
}
});//$.ajax()
// We have to create a link to the file
downloadLink.href = window.URL.createObjectURL(csvFile);
// Make sure that the link is not displayed
downloadLink.style.display = "none";
// Add the link to your DOM
document.body.appendChild(downloadLink);
// Lanzamos
downloadLink.click();
}
controller:
#Controller
public class MainController {
#RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
#ResponseBody
public ResponseEntity<?> uploadFile(
#RequestParam("filename") MultipartFile uploadfile) {
try {
// Get the filename and build the local file path
String filename = uploadfile.getOriginalFilename();
String directory = env.getProperty("paths.uploadedFiles");
String filepath = Paths.get(directory, filename).toString();
// Save the file locally
BufferedOutputStream stream =
new BufferedOutputStream(new FileOutputStream(new File(filepath)));
stream.write(uploadfile.getBytes());
stream.close();
}
catch (Exception e) {
System.out.println(e.getMessage());
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
}
return new ResponseEntity<>(HttpStatus.OK);
}
}
application.resources:
paths.uploadedFiles = /resources/test/
POST http://localhost:8000/uploadFile 400 (Bad Request)
error data: {"readyState":4,"responseText":"{\"timestamp\":1511523835282,\"status\":400,\"error\":\"Bad Request\",\"exception\":\"org.springframework.web.bind.MissingServletRequestParameterException\",\"message\":\"Required MultipartFile parameter 'filename' is not present\",\"path\":\"/uploadFile\"}","responseJSON":{"timestamp":1511523835282,"status":400,"error":"Bad Request","exception":"org.springframework.web.bind.MissingServletRequestParameterException","message":"Required MultipartFile parameter 'filename' is not present","path":"/uploadFile"},"status":400,"statusText":"Bad Request"}
Hello everyone i am using angularjs java and rest to implement one report. Based on UI field selected there is a call to Java Layer and from java there is some database call and the returned input stream i am downloading in a csv file.
There is one problem happening if i do the same with hitting the the same url by browser which i m passing through angularjs than i m able to download the file but if by using UI i m making the request than there is no download option and data is returned as a stream in http response to angular.
java code:
enter code here
#Path("/files")
public class DownloadCsvFile {
#GET
#Path("/csv")
#Produces({MediaType.APPLICATION_OCTET_STREAM})
public Response getFile() {
StreamingOutput outp = new StreamingOutput() {
#Override
public void write(OutputStream out) throws IOException,
WebApplicationException {
String url ="http://someurl?
indent=on&q=RCE_POST:2016&sort=id%20asc
&rows=100000&start=0&wt=csv";
final InputStreamReader is = new InputStreamReader(
((HttpURLConnection) (new URL(url)).openConnection())
.getInputStream(),
Charset.forName("UTF-8"));
IOUtils.copy(is, out);
}
};
ResponseBuilder response = Response.ok(outp);
response.header("Content-Disposition", "attachment;
filename=\"testFile_file.csv\"");
return response.build();
} }
AngularJs controller code :
enter code here
var app = angular.module('myApp', ['ngProgress']);
app.controller('myCtrl', function($scope,$http,ngProgressFactory) {
// on submit the fun is called
$scope.LMALLPeriodReport =function()
{
return $http.get("http://localhost:8080/IsaveIdeas/rest/files/csv?
parameters="+parameter)
//parameter contain the selected field in UI
.then(function (response) {
var result = response.data;
alert("printing data");
});
};
The same request from the browser http://localhost:8080/IsaveIdeas/rest/files/csv? parameters={parameter} enable me to download the file.
You can use Blob in your angularjs code like this:
....
.then(function (response) {
var fileName = "yourFileName.csv";
var a = document.createElement("a");
document.body.appendChild(a);
response.data = "\ufeff" + response.data;
var file = new Blob([response.data], {encoding:"UTF-8",type:'application/csv;charset=UTF-8'});
var fileURL = URL.createObjectURL(file);
a.href = fileURL;
a.download = fileName;
a.click();
}
My problem is that I am getting the wrong sized file on the client side. Here is my #Controller ...
#RequestMapping(value = "/download/{id}", method = RequestMethod.GET)
public ResponseEntity<?> download(final HttpServletRequest request,
final HttpServletResponse response,
#PathVariable("id") final int id) throws IOException {
try {
// Pseudo-code for retrieving file from ID.
Path zippath = getZipFile(id);
if (!Files.exists(zippath)) {
throw new IOException("File not found.");
}
ResponseEntity<InputStreamResource> result;
return ResponseEntity.ok()
.contentLength(Files.size(zippath))
.contentType(MediaType.APPLICATION_OCTET_STREAM)
.body(new InputStreamResource(new FileInputStream(zippath.toFile())));
} catch (Exception ex) {
// ErrorInfo is another class, unimportant
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(new ErrorInfo(ex));
}
}
... and here is my client-side code using angular-file-saver ...
$http({url: "export/download/" + exportitem.exportId, withCredentials: true})
.then(function(response) {
function str2bytes(str) {
var bytes = new Uint8Array(str.length);
for (var i=0; i<str.length; i++) {
bytes[i] = str.charCodeAt(i);
}
return bytes;
}
var blob = new Blob([str2bytes(response.data)], {type: 'application/octet-stream'});
FileSaver.saveAs(blob, "download.zip");
}, $exceptionHandler);
The original file is 935673 bytes but response.data is 900728 and passing it through the transformation to Uint8Array results in a Blob that is 900728 in size as well. Either way, the resulting saved file is 900728 bytes (34945 bytes shy). Also it is not quite the same in what gets written. It seems to slightly get bloated but then the last part just seems to be truncated. Any ideas what I might be doing wrong?
UPDATE
I just updated my controller method to be the following and got the exact same result. Grrr.
#RequestMapping(value = "/download/{id}", method = RequestMethod.GET)
public void download(final HttpServletRequest request,
final HttpServletResponse response,
#PathVariable("id") final int id) throws IOException {
// Pseudo-code for retrieving file from ID.
Path zippath = getZipFile(id);
if (!Files.exists(zippath)) {
throw new IOException("File not found.");
}
response.setContentType("application/zip");
response.setHeader("Content-Disposition",
"attachment; filename=download.zip");
InputStream inputStream = new FileInputStream(zippath.toFile());
org.apache.commons.io.IOUtils.copy(inputStream, response.getOutputStream());
response.flushBuffer();
inputStream.close();
}
So the problem turned out to be angular's $http service. I also tried jQuery's ajax method. Both gave the same result. If I instead use the native XMLHttpRequest it works correctly. So the Java code was sound. I first verified this by exposing the file directly to the internet and then both using curl and directly accessing in the browser I managed to download the file of the correct size. Then I found this solution so that I could also download the file via javascript.
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.responseType = "blob";
xhr.withCredentials = true;
xhr.onreadystatechange = function (){
if (xhr.readyState === 4) {
var blob = xhr.response;
FileSaver.saveAs(blob, filename);
}
};
xhr.send();
Why does angular or jQuery give the wrong result? I still don't know but if anyone wishes to give an answer that uses those it would be appreciated.
responseType: blob
did the trick for a zip file
Angular 2 +
this.http.get('http://localhost:8080/export', { responseType: ResponseContentType.Blob })
.subscribe((res: any) => {
const blob = new Blob([res._body], { type: 'application/zip' });
saveAs(blob, "fileName.zip");
i just stumbled over the 'responseType' in $http requests, you are probably looking for 'blob': https://docs.angularjs.org/api/ng/service/$http#usage
By following this link PLUNKER . I want to show pdf file in new window, but I want to read the pdf file from server
My service code
#RequestMapping(value = "/retrievePDFFile", method = RequestMethod.GET)
public #ResponseBody
InputStream retrievePDFFile() throws FileNotFoundException
{
InputStream inputStream = new FileInputStream("/resources/AngularJS 2013.pdf");
return inputStream;
}
My angular controller
$http({
method : "GET",
url : "/service/retrievePDFFile"
}).success(function(data) {
console.log(data);
}).error(function(data, status) {
console.log(data);
});
I got the pdf input stream from server like this..
How to read this, and open as a PDF file in new tab or window..
Thanks
After lot of searching I achieved the goal by little bit change in my controller code
$http.get('/retrievePDFFiles', {responseType: 'arraybuffer'})
.success(function (data) {
var file = new Blob([data], {type: 'application/pdf'});
var fileURL = URL.createObjectURL(file);
window.open(fileURL);
});
I'm using Phonegap with javascript and jquery. I've created a java servlet, it returns a pdf file. I can get de file correctly in a browser but I can't on Phonegap.
My code is this (javascript):
$.ajax({
type: "GET",
url: "http://x.x.x.x:xxxx/MyApp/PDF",
success: function(data, textStatus, request) {
alert("pdf OK");
window.open(data, "_system");
},
error: function(data, textStatus, request) {
alert("pdr error");
}
And here the servlet (this works fine from browser):
protected void doGet(HttpServletRequest req, HttpServletResponse response) throws ServletException, IOException {
try {
// Create PDF (this works fine)
String ruta = getServletContext().getRealPath(reportTemplateUrl);
InputStream resourceAsStream = new FileInputStream(ruta);
jasperDesign = JRXmlLoader.load(resourceAsStream);
jasperReport = JasperCompileManager.compileReport(jasperDesign);
jasperPrint = JasperFillManager.fillReport(jasperReport, null, new JRBeanCollectionDataSource(findReportData(name)));
File pdf = new File("output.pdf");
JasperExportManager.exportReportToPdfStream(jasperPrint, new FileOutputStream(pdf));
// Send PDF
response.setContentType("application/pdf");
response.addHeader("Content-Disposition", "attachment; filename=output.pdf");
response.setContentLength((int) pdf.length());
InputStream fileInputStream = new FileInputStream(pdf);
OutputStream responseOutputStream = response.getOutputStream();
int bytes;
while ((bytes = fileInputStream.read()) != -1) {
responseOutputStream.write(bytes);
}
System.out.println("CREATED!");
} catch (JRException e) {
e.printStackTrace();
}
This code is running on iPad with Phonegap and always I get the OK alert. From the iPad's browser I can donwload and read the pdf (I put the URL in the browser as a normal page) and all is OK.
I think the problem is the "data", from javascript, I don't know if I need to save the file first or how to do to show it...
And yes, I need use a servlet and ajax, the PDF is dynamic. I don't mind open it with internal or external browser, but I need to see it.
Thanks!
:)
Well, I solved this doing a GET call on javascript opening the url on a new browser:
window.open("http://.../PDF?id=id&name=name&...", "_blank");
Without ajax.
Thanks everyone