JSP Servlet response pdf to Jquery - java

I have a jsp page with a button, that link on a servlet and this create a pdf file an stream that as respons.
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
path = request.getServletContext().getRealPath("/");
String pdfFileName = "foo.pdf";
String contextPath = getServletContext().getRealPath(File.separator);
File pdfFile = new File(path + pdfFileName);
response.setContentType("application/pdf");
response.addHeader("Content-Disposition", "attachment; filename=" + pdfFileName);
response.setContentLength((int) pdfFile.length());
FileInputStream fileInputStream = new FileInputStream(pdfFile);
OutputStream responseOutputStream = response.getOutputStream();
int bytes;
while ((bytes = fileInputStream.read()) != -1) {
responseOutputStream.write(bytes);
}
}
the jquery is
$(document).ready(function() {
$(".getpdfbutton").click(function(){
var currentRow=$(this).closest("tr");
var col1=currentRow.find("td:eq(0)").html();
var data3=col1;
alert(data3);
$.get("PDFerzeugen",{Spass:data3}, function(data) {
/* window.location = data; */
alert(data);
});
});
I get the data respons as base64 , how can i download it as pdf file ?

i solved it over this script
function SaveToDisk(fileURL, fileName) {
// for non-IE
if (!window.ActiveXObject) {
var save = document.createElement('a');
save.href = fileURL;
save.target = '_blank';
save.download = fileName || 'unknown';
var evt = new MouseEvent('click', {
'view': window,
'bubbles': true,
'cancelable': false
});
save.dispatchEvent(evt);
(window.URL || window.webkitURL).revokeObjectURL(save.href);
}
// for IE < 11
else if ( !! window.ActiveXObject && document.execCommand) {
var _window = window.open(fileURL, '_blank');
_window.document.close();
_window.document.execCommand('SaveAs', true, fileName || fileURL)
_window.close();
}
};

Related

Java export Excel by browser

I want to export Excel by browser. If I click the export button I can see information in Chrome network, but it did not download. I can download excel to my project folder, but how to export excel through the browser? Below the Ajax and controller codes.
This is my Excel util:
public class WriteExcel {
/**
* #param answerList
* #return
*/
public static void writeData(List<Answer> answerList, String paperName, HttpServletResponse response) throws IOException {
Workbook workbook = new HSSFWorkbook();
Sheet sheet = workbook.createSheet("test");
for(int i=0; i<answerList.size();i++){
Answer answer = answerList.get(i);
Row row = sheet.createRow(i);
Cell cell = row.createCell(0);
cell.setCellValue(answer.getAnswerpname());
List<AnswerReceive> answerReceives = JSON.parseArray(answer.getAnswerdata(), AnswerReceive.class);
for(int j=0; j<answerReceives.size(); j++){
AnswerReceive answerReceive = answerReceives.get(j);
Cell tmp_cell = row.createCell(j+1);
tmp_cell.setCellValue(answerReceive.getData());
}
}
response.setContentType("application/octet-stream;charset=UTF-8");
response.setHeader("Content-Disposition", "attachment;filename="
.concat(String.valueOf(URLEncoder.encode(paperName, "UTF-8"))));
OutputStream out = response.getOutputStream();
workbook.write(out);
}
}
My controller:
#PostMapping("/export")
#ResponseBody
public Object exportExcel(#RequestParam("paperId") String paperId, HttpServletResponse response) throws IOException {
List<Answer> answerList = answerService.getData(paperId);
WriteExcel.writeData(answerList, "test", response);
}
My Ajax:
$("button[name='export']").click(function () {
$.ajax({
url: "/export",
type: "post",
data: {"paperId":$(this).attr("data-paper-id")},
success: function (data) {
console.log(data.flag);
console.log(data.Message);
}
})
})
Try following:
But you Apaches FileUtils for it
#PostMapping("/export", produdes = MediaType.APPLICATION_JSON_VALUE)
#ResponseBody
public Object exportExcel(#RequestParam("paperId") String paperId, HttpServletResponse response) throws IOException {
List<Answer> answerList = answerService.getData(paperId);
InputStream excelFile = WriteExcel.writeData(answerList, "test", response);
response.setHeader("Content-Disposition", "attachment; filename=Export" + LocalDate.now() + ".xlsx");
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
FileCopyUtils.copy(excelFile, response.getOutputStream());
response.flushBuffer();
}
To create an Inputstream, attach to your writeData Funcion:
ByteArrayInputStream bais = null;
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
workbook.write(baos);
baos.flush();
byte[] buffer = baos.toByteArray();
bais = new ByteArrayInputStream(buffer);
baos.close();
} catch (IOException e) {
e.printStackTrace();
}
return bais;
you button should be somethin like this
<button target='_blank' href='/export'>
on server I would make this
response.contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
response.addHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=exceptions.xlsx")
response.flushBuffer();
Look at Download File Using Javascript/jQuery
Actually, if your headers are specified correctly, your file download should be started after clicking given element with corresponding href (in new tab) below code for starting download in the same tab.
I would recomend to use tools like that
http://jqueryfiledownload.apphb.com.
or through axios
axios.post("/yourUrl"
, data,
{responseType: 'blob'}
).then(function (response) {
let fileName = response.headers["content-disposition"].split("filename=")[1];
if (window.navigator && window.navigator.msSaveOrOpenBlob) { // IE variant
window.navigator.msSaveOrOpenBlob(new Blob([response.data], {type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'}),
fileName);
} else {
const url = window.URL.createObjectURL(new Blob([response.data], {type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'}));
const link = document.createElement('a');
link.href = url;
link.setAttribute('download', response.headers["content-disposition"].split("filename=")[1]); //you can set any name(without split)
document.body.appendChild(link);
link.click();
}
}
);

export file head line has extra row

I want to export odsfile like this
but I really got export is this(head line has extra word)
here is my code,Thanks for any suggestion
#RequestMapping(value = "/export", method = RequestMethod.POST)
public #ResponseBody void exportOds(Long questionId,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
VoteQuestion q = voteManager.getQuestion(questionId);
TableModel model = new DefaultTableModel(1000,1000);
File file = File.createTempFile("temp", ".ods");
model.setValueAt(q.getQuestion(), 0, 0);
int row = 2;
for (VoteOption opt : q.getOptions()) {
model.setValueAt(opt.getDescription(), row, 0);
model.setValueAt(opt.getVotes(), row++, 1);
}
SpreadSheet.createEmpty(model).saveAs(file);
String fileName = "投票結果";
String encodeFileName = FilenameEncoder.getInstance(request)
.encodeFileName(fileName + ".ods");
response.setHeader("Content-Disposition",
"attachment; filename=" + encodeFileName);
FileInputStream in = null;
OutputStream out = null;
try {
out = response.getOutputStream();
in = new FileInputStream(file);
IOUtils.copy(in, out);
} finally {
IOUtils.closeQuietly(in);
IOUtils.closeQuietly(out);
file.deleteOnExit();
}
}
Solved by this code
#RequestMapping(value = "/export", method = RequestMethod.POST)
public #ResponseBody void exportOds(Long questionId,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
VoteQuestion q = voteManager.getQuestion(questionId);
String[] columName = new String[1000];
columName[0] = q.getQuestion();
for(int i = 1 ;i<1000;i++){
columName[i] = "";
}
TableModel model = new DefaultTableModel(columName,1000);
File file = File.createTempFile("temp", ".ods");
int row = 1;
for (VoteOption opt : q.getOptions()) {
model.setValueAt(opt.getDescription(), row, 0);
model.setValueAt(opt.getVotes(), row++, 1);
}
SpreadSheet.createEmpty(model).saveAs(file);
String fileName = "投票結果";
String encodeFileName = FilenameEncoder.getInstance(request)
.encodeFileName(fileName + ".ods");
response.setHeader("Content-Disposition",
"attachment; filename=" + encodeFileName);
FileInputStream in = null;
OutputStream out = null;
try {
out = response.getOutputStream();
in = new FileInputStream(file);
IOUtils.copy(in, out);
} finally {
IOUtils.closeQuietly(in);
IOUtils.closeQuietly(out);
file.deleteOnExit();
}
}

java.io.FileNotFoundException: In Netbeans glashfish server

I'm very new to JAVA. I tried to save image through Java servlet and Ajax in netbeans. In netbeans I tried same coding with tomcat server is working fine.If I use Glashfish it's throwing error. Below is my coding.
Servlet:
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Part img = request.getPart("img");
String id = (String) request.getParameter("ids");
out.println(saveImage(img, "E:\\Users\\XXXX\\Desktop\\wine_shop\\build\\web\\images\\wines"));
}
Save image method:
private String saveImage(Part img, String path) throws IOException {
File fileSaveDir = new File(path);
if (!fileSaveDir.exists()) {
fileSaveDir.mkdirs();
}
System.out.println("Upload File Directory=" + fileSaveDir.getAbsolutePath());
String fileName = null;
fileName = extractFileName(img);
img.write(path+ fileName);
return "1";
}
My Error:
java.io.FileNotFoundException: E:\Users\xxxx\AppData\Roaming\NetBeans\8.2\config\GF_4.1.1\domain1\generated\jsp\wine_shop\E:\Users\xxxx\Desktop\wine_shop\build\web\images\winesth.jpg (The filename, directory name, or volume label syntax is incorrect)
Help to fix this..
Try This Code..
#WebServlet(name = "abc", urlPatterns = {"/upload"})
#MultipartConfig
public class abc extends HttpServlet {
private final static Logger LOGGER =
Logger.getLogger(abc.class.getCanonicalName());
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
final String path = "E:\\shopping\\web\\admin\\img";
final Part filePart = request.getPart("file");
final String fileName = getFileName(filePart);
OutputStream out = null;
InputStream filecontent = null;
final PrintWriter writer = response.getWriter();
try {
out = new FileOutputStream(new File(path + File.separator
+ fileName));
filecontent = filePart.getInputStream();
int read = 0;
final byte[] bytes = new byte[1024];
while ((read = filecontent.read(bytes)) != -1) {
out.write(bytes, 0, read);
}
writer.println("New file " + fileName + " created at " + path);
LOGGER.log(Level.INFO, "File{0}being uploaded to {1}",
new Object[]{fileName, path});
} catch (FileNotFoundException fne) {
writer.println("<br/> ERROR: " + fne.getMessage());
}
}
private String getFileName(final Part part) {
final String partHeader = part.getHeader("content-disposition");
LOGGER.log(Level.INFO, "Part Header = {0}", partHeader);
for (String content : part.getHeader("content-disposition").split(";")) {
if (content.trim().startsWith("filename")) {
return content.substring(
content.indexOf('=') + 1).trim().replace("\"", "");
}
}
return null;
}

Java servlet doesn't render mp4 in safari with html5 video tag

The html5 video tag fails to load mp4 from servlet.
My servlet code
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Enumeration<String> enumn = request.getHeaderNames();
while(enumn.hasMoreElements()){
String hr = enumn.nextElement();
System.out.println(hr + " - "+request.getHeader(hr));
}
String fileName = "test.mp4";
String filePath = "/Users/home/Downloads/test.mp4";
String range = request.getHeader("range");
File file = new File (filePath) ;
long fileLength = file.length();
response.setContentType("video/mp4");
response.setHeader("Pragma", "no-cache");
response.setHeader("Cache-control", "private");
response.setHeader("Set-Cookie", "fileDownload=true; path=/");
response.setDateHeader("Expires", 0);
response.setHeader("Content-Disposition", "attachment; filename=\""+ fileName+"\"");
response.setHeader("Accept-Ranges", "bytes");
response.setHeader("Etag", "W/\"9767057-1323779115364\"");
response.setHeader("Connection", "keep-alive");
response.setBufferSize((int)fileLength + 200);
response.setContentLength((int)fileLength);
response.setHeader("Content-Type", "video/mp4" );
response.setHeader("Content-Length", String.valueOf( file.length()));
BufferedInputStream input = null ;
BufferedOutputStream output = null;
try {
input = new BufferedInputStream( new FileInputStream(file) );
output = new BufferedOutputStream(response.getOutputStream());
byte[] buffer = new byte[(int)fileLength];
for (int length = 0 ; (length = input.read(buffer)) > 0 ;) {
output.write(buffer, 0, length);
}
response.flushBuffer();
System.out.println("buffer length : "+buffer.length);
response.setHeader("Content-Range", "0-"+ Integer.valueOf(buffer.length-1));
System.out.println("=======================================================================");
for(String hr : response.getHeaderNames()){
System.out.println(hr + " - "+response.getHeader(hr));
}
} catch (Exception e){
e.printStackTrace();
} finally {
if (output != null) try { output.close(); } catch (IOException logOrIgnore) {}
if (input != null) try { input.close(); } catch (IOException logOrIgnore) {}
}
}
Video Tag
It is working fine in firefox and chrome. But safari is failing to load the video.

ExtJS Handling Response Holding PDF as StreamingOutput

I am working with extJS 4.2.1 and I would like to display a PDF file that is stored in a ResponseBuilder as a StreamingOutput object. When the response is returned to the extjs controller, Im not sure how to handle it in order to display the PDF on a new page.
#GET
#Path("/images/{imageNumber}/{imageType}")
#Produces({"application/pdf"})
public Response openDocument(#PathParam("company") String company,
#PathParam("imageNumber") String imageNumber, #PathParam("imageType") String imageType){
final File imageFile = new File("/someRemoteDir/28717484.pdf");
StreamingOutput stream = new StreamingOutput() {
public void write(OutputStream output) throws IOException, WebApplicationException {
try {
InputStream input = new FileInputStream(imageFile);
byte[] buf = new byte[8192];
int c = 0;
while ((c = input.read(buf, 0, buf.length)) > 0) {
output.write(buf, 0, c);
output.flush();
}
output.close();
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
};
ResponseBuilder response = Response.ok(stream);
response.type("application/pdf");
response.status(200);
response.header("Accept-Ranges","bytes");
response.header("Cache-Control",null);
response.header("Pragma",null);
response.header("Content-Disposition","inline; filename=\"" + imageDoc.getNumber() +"\"");
return response.build();
}
extJS controller
Ext.Ajax.request({
method: 'GET',
url: CTrack.Config.appPath('loads/images/' + imageNumber + '/' + imageType),
jsonSubmit: true,
success: function(response, opt) {
if (response.status == 200) {
NOT SURE WHAT TO DO HERE?.........
} else {
me.displayError(errorMsg);
} },
failure: function(response, opt) {
console.log('Failure');
}
...

Categories

Resources