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();
}
}
Related
I have a file txt on the server (previously generated). When user clicks on button it generates the file, now I want (additionally) download the file inside my function. But I can't make it work(I'm new on JAVA EE), cause I don't know how to get HttpServletResponse.
From web I call function with this:
#Path("getreport")
#POST
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
public JSONObject getreport(CommonInput input) {
JSONObject j = objectmapper.conertValue(reportBean.getreport(),JSONObject.class);
return j;
}
reprotBean has function:
public void getreport() {
//...doing many things
//generating my file
List<String> lines = new ArrayList<>();
lines.add("star file");
//..adding many lines
Path file = Paths.get("C:\\Users\\myuser\\file.txt");
Files.write(file, lines, StandardCharsets.UTF_8);
downloadFile();
//...doing many things
}
I found this way to download my file:
public void downloadFile(HttpServletResponse response){
String sourceFile = ""C:\\Users\\myuser\\file.txt"";
try {
FileInputStream inputStream = new FileInputStream(sourceFile);
String disposition = "attachment; fileName=outputfile.txt";
response.setContentType("text/txt");
response.setHeader("Content-Disposition", disposition);
response.setHeader("content-Length", String.valueOf(stream(inputStream, response.getOutputStream())));
} catch (IOException e) {
logger.error("Error occurred while downloading file {}",e);
}
}
private long stream(InputStream input, OutputStream output) throws IOException {
try (ReadableByteChannel inputChannel = Channels.newChannel(input); WritableByteChannel outputChannel = Channels.newChannel(output)) {
ByteBuffer buffer = ByteBuffer.allocate(10240);
long size = 0;
while (inputChannel.read(buffer) != -1) {
buffer.flip();
size += outputChannel.write(buffer);
buffer.clear();
}
return size;
}
}
When I try to use downloadFile(), it requires HttpServletResponse, and I don't have that parameter. I can't understand how to get that (how it works), or do I have to use another method for download my file?
All solutions I found requires HttpServletResponse (download files from browsers)
If you have that file generated already. Just need write it to HttpServletResponse
resp.setContentType("text/plain");
resp.setHeader("Content-disposition", "attachment; filename=sample.txt");
try(InputStream in = req.getServletContext().getResourceAsStream("sample.txt");
OutputStream out = resp.getOutputStream()) {
byte[] buffer = new byte[ARBITARY_SIZE];
int numBytesRead;
while ((numBytesRead = in.read(buffer)) > 0) {
out.write(buffer, 0, numBytesRead);
}
}
Be sure to make your file to be accessed by ServeletContext
If you are using Spring Rest framework. Can refer to below
#GetMapping("/download")
public ResponseEntity<byte[]> downloadErrorData() throws Exception {
List<Employee> employees = employeeService.getEmployees();
ObjectMapper objectMapper = new ObjectMapper();
String json = objectMapper.writeValueAsString(employees);
byte[] isr = json.getBytes();
String fileName = "employees.json";
HttpHeaders respHeaders = new HttpHeaders();
respHeaders.setContentLength(isr.length);
respHeaders.setContentType(new MediaType("text", "json"));
respHeaders.setCacheControl("must-revalidate, post-check=0, pre-check=0");
respHeaders.set(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + fileName);
return new ResponseEntity<byte[]>(isr, respHeaders, HttpStatus.OK);
}
credit to: https://www.jeejava.com/file-download-example-using-spring-rest-controller/
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();
}
}
);
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;
}
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();
}
};
i have followed this to upload file to server. the file is getting uploaded but after uploading the file it gives the page name as the filename.extension.jsp and gives HTTP Status 404 here is the screen shot :
But i want to show the user only the status message saying File is uploaded. how to do this?
Here is my spring controller method:
#RequestMapping(value = "/CIMtrek_Compliance_Daily_Shipments_FileUpload", method = RequestMethod.POST)
public String createComments(
#RequestParam("CIMtrek_daily_originator_comments") MultipartFile uploadItem,
HttpServletRequest request) {
String uploadedFileName = "";
try {
String fileName = null;
InputStream inputStream = null;
OutputStream outputStream = null;
if (uploadItem.getSize() > 0) {
inputStream = uploadItem.getInputStream();
fileName = request.getRealPath("") + "/resources/Attachment/"+uploadItem.getOriginalFilename();
outputStream = new FileOutputStream(fileName);
int readBytes = 0;
byte[] buffer = new byte[10000];
while ((readBytes = inputStream.read(buffer, 0, 10000)) != -1) {
outputStream.write(buffer, 0, readBytes);
}
outputStream.close();
inputStream.close();
}
uploadedFileName = uploadItem.getOriginalFilename();
} catch (Exception e) {
e.printStackTrace();
}
return uploadedFileName;
}
Please help me to find,
Best Regards
Hi #Anto you can do it somethig like this,
#RequestMapping(value = "/CIMtrek_Compliance_Daily_Shipments_FileUpload", method = RequestMethod.POST)
public String createComments(
#RequestParam("CIMtrek_daily_originator_comments") MultipartFile uploadItem,
HttpServletRequest request, ModelMap map) {
String uploadedFileName = "";
...
uploadedFileName = uploadItem.getOriginalFilename();
// ---------------------------------------------------------------------------
if("" != uploadedFileName || null != uploadedFileName) {
map.put("message", new String("File is uploaded."));
} else {
map.put("message", new String("File is not uploaded."));
}
// ---------------------------------------------------------------------------
} catch (Exception e) {
e.printStackTrace();
}
return uploadedFileName;
}
And JSP you put
<c:out value="${message}"></c:out>
I hope help you :)