How do i return a powerpoint (.pptx) file from REST response in springMVC - rest

I am generating a powerpoint file(.pptx) and i would like to return back this file when a REST call happens. But now am able to get only .File type extension.
#RequestMapping(value = "/ImageManagerPpt/{accessionId}", method = RequestMethod.GET, produces = "application/ppt")
public ResponseEntity<InputStreamResource> createPptforAccessionId(#PathVariable("accessionId") String accessionId,HttpServletResponse response) throws IOException** {
System.out.println("Creating PPT for Patient Details with id " + accessionId);
File pptFile = imageManagerService.getPptForAccessionId(accessionId);
if (pptFile == null) {
System.out.println("Patient Id with id " + accessionId + " not found");
return new ResponseEntity<InputStreamResource>(HttpStatus.NOT_FOUND);
}
InputStream stream = null;
try {
stream = new FileInputStream(pptFile);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ClassPathResource classpathfile = new ClassPathResource("Titlelayout3.pptx");
InputStreamResource inputStreamResource = new InputStreamResource(stream);
return ResponseEntity.ok().contentLength(classpathfile.contentLength())
.contentType(MediaType.parseMediaType("application/octet-stream"))
.body(new InputStreamResource(classpathfile.getInputStream()));
}
-Bharat

Have you tried, this?
InputStream stream = new InputStream(pptFile);
org.apache.commons.io.IOUtils.copy(is, response.getOutputStream());
response.flushBuffer();
You will get file as you put into the InputStream.

Related

I have json values , how to save into mongodb using spring mvc

I have class like "location".
"Location" class have four field.
fields are:id,city,state,country..
country is seprate class it contains 2 field , country code, country name , 2 fields must read from location class..
if i write "locationMongoRepository.save()", then it shows error as bound mismatch. please give solution for how to save in mongodb.
public void insertLocation() throws InvalidFormatException, IOException, JSONException{
FileInputStream inp;
Workbook workbook;
try {
inp = new FileInputStream( "/home/Downloads/eclipse/Workspace/Samplboot-master latest/cityListForIndia1.xlsx" );
workbook = WorkbookFactory.create( inp );
Sheet sheet = workbook.getSheetAt(0);
JSONArray json = new JSONArray();
boolean isFirstRow = true;
ArrayList<String> rowName = new ArrayList<String>();
for ( Iterator<Row> rowsIT = sheet.rowIterator(); rowsIT.hasNext(); )
{
Row row = rowsIT.next();
JSONObject jRow = new JSONObject();
if(isFirstRow)
{
for ( Iterator<Cell> cellsIT = row.cellIterator(); cellsIT.hasNext(); )
{
Cell cell = cellsIT.next();
rowName.add(cell.getStringCellValue());
}
isFirstRow = false;
}
else
{
JSONObject jRowCountry= new JSONObject();
JSONObject jRowLocation= new JSONObject();
jRowLocation.put("city", row.getCell(0));
jRowLocation.put("state", row.getCell(1));
jRowCountry.put("country",row.getCell(2) );
jRowCountry.put("countryCode", row.getCell(3) );
jRowLocation.put("country", jRowCountry);
System.out.println("Location"+jRowLocation.toString());
}
}
}
catch (InvalidFormatException e) {
// TODO Auto-generated catch block
System.out.println("Invalid Format, Only Excel files are supported");
e.printStackTrace();
} catch (IOException e) {
System.out.println("Check if the input file exists and the path is correct");
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
System.out.println("Unable to generate Json");
e.printStackTrace();
}
}
}
I'm using Spring Data to support working with MongoDB and it's really helpful. You should read this article to get its idea and applied to your case https://dzone.com/articles/spring-data-mongodb-hello.
P/S: In case you can't use Spring Data to work with MongoDB, please provide more detail in your code/ your exception so we can investigate it more detail.

Uploading file whose name is in unicode

I have some JavaScript code that upload file to server using ajax and form data and server side java code that accept it. I can upload English file name. But when I uploaded other Unicode file name, the file name I got in server side is unreadable. The following is code snippet.
JavaScript
var f = new FormData();
f.append("file", file);
xhr.send(f);
Java
public void upload(MultipartFormDataInput input) {
Map<String, List<InputPart>> uploadForm = input.getFormDataMap();
List<InputPart> inputParts = uploadForm.get("user_file[]");
IFileInfo file = null;
for (InputPart inputPart : inputParts) {
try {
MultivaluedMap<String, String> header = inputPart.getHeaders();
fileName = getFileName(header);
System.out.println("File name is " + fileName);
} catch (IOException e) {
e.printStackTrace();
}
}
}
private String getFileName(MultivaluedMap<String, String> header) {
System.out.println("Headers is " + header.getFirst("Content-Disposition"));
String[] contentDisposition = header.getFirst("Content-Disposition")
.split(";");
for (String filename : contentDisposition) {
if ((filename.trim().startsWith("filename"))) {
String[] name = filename.split("=");
String finalFileName = name[1].trim().replaceAll("\"", "");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return finalFileName;
}
}
return "unknown";
}
When I upload "大家好.jpg" , I got server side log showing the following.
Headers is form-data; name="user_file[]"; filename="���������.jpg"
File name is ���������.jpg
I think browser encode file name before uploading it.But I don't know which encoding did it used or how to decode it back. Any help is much appreciated.

wicket response trimmed at the end

I have a trouble with output data in response.
#Override
protected ResourceResponse newResourceResponse(Attributes attributes) {
ResourceResponse response = new ResourceResponse();
response.setContentDisposition(ContentDisposition.INLINE);
response.disableCaching();
StringBuilder stringBuilder = new StringBuilder(DEFAULT_CONTENT_TYPE);
stringBuilder.append(";").append(charset == null ? DEFAULT_CHARSET : charset);
response.setContentType(stringBuilder.toString());
response.setLastModified(Time.now());
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
try {
fillOutputStream(outputStream);
} catch (IOException e) {
logger.error("Error when try to fill data for html report", e);
}
String message = null;
try {
message = outputStream.toString("UTF-8");
} catch (UnsupportedEncodingException e) {
logger.warn("Unknown encoding");
message = outputStream.toString();
}
final CharSequence data = message;
response.setContentLength(data.length());
response.setWriteCallback(new WriteCallback() {
#Override
public void writeData(Attributes attributes) {
attributes.getResponse().write(data);
}
});
configureResponse(response, attributes);
return response;
}
Here data is html page which has been generated in fillOutputStream() method and transform to CharSequence.
I've logged the data and it have correct content which I expect but in the result I have trimmed at the end page.
The length of String is not necessarily equal to its byte count.
Use a CountingOutputStream instead (e.g. from guava).

I have jsp oage which upload form data and file upload also same time. But i got java.io.FileNotFoundException: when there isn't file upload

boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if (isMultipart) {
System.out.println("multipart2");
// Create a factory for disk-based file items
FileItemFactory factory = new DiskFileItemFactory();
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
try {
// Parse the request
List /* FileItem */ items = upload.parseRequest(request);
Iterator iterator = items.iterator();
while (iterator.hasNext()) {
FileItem item = (FileItem) iterator.next();
if (item.isFormField()) //your code for getting form fields
{
if (item.getFieldName().equals("btn")) {
if (item.getString().equals("Submit")) {
String name = item.getFieldName();
String value = item.getString();
System.out.println("test2" + name + value);
}
if (item.getString().equals("Save as Draft")) {
System.out.println("hii hii2");
String name = item.getFieldName();
String value = item.getString();
}
}
} if (!item.isFormField()) {
String fileName = item.getName();
System.out.println("File Upload Named : " + fileName);
String root = getServletContext().getRealPath("/");
File path = new File(root + "/uploads");
if (!path.exists()) {
boolean status = path.mkdirs();
}
File uploadedFile = new File(path + "/" + fileName);
// System.out.println(uploadedFile.getAbsolutePath());
item.write(uploadedFile);
}
}
} catch (FileUploadException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
response.sendRedirect("/EventCalendar-war/pages/user_pages/user_create_event.jsp");
}
This is my code.When there is no file to upload I got java.io.FileNotFoundException .If file is upload with form data it's work fine.What is wrong with my code?

Send a file from server to client in GWT

I am using GWT.
I have to download a file file from server to client.
Document is in the external repository.
Client sends the id of the document through a Servlet.
On server side: Using this ID document is retrieved:
Document document = (Document)session.getObject(docId);
ContentStream contentStream = document.getContentStream();
ByteArrayInputStream inputStream = (ByteArrayInputStream) contentStream.getStream();
int c;
while ((c = inputStream.read()) != -1) {
System.out.print((char) c);
}
String mime = contentStream.getMimeType();
String name = contentStream.getFileName();
InputStream strm = contentStream.getStream();
Here I can read the document.
I want to send this to the client.
How do I make this a file and send it back to the client?
In Your Servlet:
Document document =(Document)session.getObject(docId);
ContentStream contentStream = document.getContentStream();
String name = contentStream.getFileName();
response.setHeader("Content-Type", "application/octet-stream;");
response.setHeader("Content-Disposition", "attachment;filename=\"" + name + "\"");
OutputStream os = response.getOutputStream();
InputStream is =
(ByteArrayInputStream) contentStream.getStream();
BufferedInputStream buf = new BufferedInputStream(is);
int readBytes=0;
while((readBytes=buf.read())!=-1) {
os.write(readBytes);
}
os.flush();
os.close();// *important*
return;
You can create a standard servlet (which extends HttpServlet and not RemoteServiceServlet) on server side and opportunity to submit the id as servlet parameter on client side.
Now you need after getting request create the excel file and send it to the client. Browser shows automatically popup with download dialog box.
But you should make sure that you set the right content-type response headers. This header will instruct the browser which type of file is it.
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String fileId = reguest.getParameter("fileId"); // value of file id from request
File file = CreatorExel.getFile(fileId); // your method to create file from helper class
// setting response headers
response.setHeader("Content-Type", getServletContext().getMimeType(file.getName()));
response.setHeader("Content-Length", file.length());
response.setHeader("Content-Disposition", "inline; filename=\"" + file.getName() + "\"");
BufferedInputStream input = null;
BufferedOutputStream output = null;
try {
InputStream inputStream = new FileInputStream(file);
ServletOutputStream outputStream = response.getOutputStream();
input = new BufferedInputStream(fileInput);
output = new BufferedOutputStream(outputStream);
int count;
byte[] buffer = new byte[8192]; // buffer size is 512*16
while ((count = input.read(buffer)) > 0) {
output.write(buffer, 0, count);
}
} finally {
if (output != null) {
try {
output.close();
} catch (IOException ex) {
}
}
if (input != null) {
try {
input.close();
} catch (IOException ex) {
}
}
}