I want to make a Spring Boot endpoint for downloading file. I Have tried this things but the file does not download automatically... I get only file content in the body...
#RequestMapping(value = "/files", produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
#ResponseBody
public ResponseEntity<FileSystemResource> getFile(#RequestParam(name = "start") String start) {
return new ResponseEntity<>(new FileSystemResource(myService.makeFile(start)),
HttpStatus.OK);
}
Another one that I have tried is this:
#RequestMapping(value = "/download", method = RequestMethod.GET, produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
public String download(HttpServletResponse response, #RequestParam(name = "start") String start)
{
response.setContentType("application/force-download");
FileReader fr = new FileReader(myService.makeFile(start));
return IOUtils.toString(fr);
}
I have read that MediaType.APPLICATION_OCTET_STREAM_VALUE will force it to download but nothing happened in my case.
You are on the right track, you just need to set one response header Content-Disposition to attachment; filename=YOUR_FILE_NAME.
Try This:
#RequestMapping(value = "/files", method = RequestMethod.GET, produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
public FileSystemResource getFile(#RequestParam(name = "start") String start, HttpServletResponse response) {
response.setHeader("Content-Disposition", "attachment; filename=" + "YOUR_FILE_NAME");
return new FileSystemResource(myService.makeFile(start));
}
Related
I am running a jar file .spring code for backend and react js for frontend. The code below works perfect for frontend and backend apart but what do you do if it is a jar . Only recieving "cant find file"
#RequestMapping(value = "/getPdf/{userType}/{userRoll}/{trainingFileName}", method = RequestMethod.GET)
public ResponseEntity<InputStreamResource> getPdf(#PathVariable("userType") String userType,
#PathVariable("userRoll") String userRoll,
#PathVariable("trainingFileName") String trainingFileName) throws IOException {
String fileName =trainingFileName + ".pdf";
String filePath = "TrainingDocuments/" +userType+"/"+userRoll+"/"+ trainingFileName+ "/"+ fileName;
File file = new File(filePath);
HttpHeaders headers = new HttpHeaders();
headers.add("content-disposition", "inline;filename=" +fileName);
InputStreamResource resource = new InputStreamResource(new FileInputStream(file));
return ResponseEntity.ok()
.headers(headers)
.contentLength(file.length())
.contentType(MediaType.parseMediaType("application/pdf"))
.body(resource);
}
I am trying to call a service from angularjs that produces a docx document.
Angularjs is supposed to display the save prompt of the web browser, and then save the document.
When I open the saved document, what I get in the docx file is :
Undefined
Api rest :
#RequestMapping(value = "/create-avenant",
method = RequestMethod.POST,
produces = MediaType.APPLICATION_JSON_VALUE)
#Timed
public void getAvenant(#RequestBody AvenantDTO avenant, HttpServletResponse response) {
contratService.createAvenant(response, avenant);
}
service produces a XWPFDocument and send to browser :
private void sendDocToBrowser(HttpServletResponse response, XWPFDocument doc) throws IOException {
try
{
byte[] buffer = new byte[8192];
ByteArrayOutputStream baos = new ByteArrayOutputStream();
doc.write(baos);
response.setHeader("Content-Disposition", "attachment;filename=myDoc.docx");
response.setContentType("application/docx");
ServletOutputStream outputStream = response.getOutputStream();
baos.writeTo(outputStream);
outputStream.flush();
}
finally
{
outputStream.close();
}
}
Angularjs :
Avenant.create(avenant,function(result){
var blob = new Blob([result.body], { type: 'application/docx' });
var link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
link.download = 'file.docx';
link.click();
})
I am making a rest API call using Angular. My Rest API look like as below:
#RequestMapping(value = "/getPDF/{projectId}", method = RequestMethod.POST)
public ResponseEntity<byte[]> generateReport(#PathVariable("projectId") long projectId, #RequestBody Object vo, final HttpServletRequest request) {
vo.setProjectId(projectId);
byte[] pdf = blueprintService.generateBluePrint(vo);
LOG.debug(new StringBuilder("Generating Blueprint for VO: ").append(vo).toString());
String fileName = null;
try {
ProjectDetailsVO pdvo = projectSetupService.getProjectDetails(vo.getProjectId());
fileName = new StringBuilder(pdvo.getClientName()).append("_")
.append(pdvo.getProjectName()).append("_")
.append(System.currentTimeMillis()).append(".pdf")
.toString();
} catch (Exception e) {
}
if (fileName == null || fileName.trim().isEmpty())
fileName = new StringBuilder("Project_")
.append(vo.getProjectId()).append("_")
.append(System.currentTimeMillis())
.append(".pdf").toString();
HttpHeaders headers = new HttpHeaders();
headers.add("Content-Type", "application/pdf");
String userAgent = request.getHeader("User-Agent");
if (userAgent != null && !(userAgent.contains("Firefox") && userAgent.contains("Mac"))) {
LOG.debug("Inline BP Content");
headers.add("Content-Disposition", new StringBuilder("inline; filename=\"").append(fileName).append("\"").toString());
} else {
LOG.debug("Attached BP Content");
headers.add("Content-Disposition", new StringBuilder("attachment; filename=\"").append(fileName).append("\"").toString());
}
if (pdf != null)
headers.setContentLength(pdf.length);
return new ResponseEntity<byte[]>(pdf, headers, HttpStatus.OK);
}
}
So server is setting file name for the PDF which I want to be the name of the generated PDF.
I tried below angular code:
success: function (data, status, headers, config) {
$modalInstance.close();
var file = new Blob([data], {type: 'application/pdf'});
var fileURL = URL.createObjectURL(file);
window.open(fileURL);
}
It works fine but it open the pdf of it's own name. Which I think, since Angular is converting the response into PDF. Hence Headers are getting excluded.
Is there any way to make a post request so it will open a PDF in new browser tab some code like as below:
$http.post{
url: myRestURL,
data: postbodyData,
taget: _blank
}
which will open my rest URL in new tab and show the PDF in browser.
Thank you.
I want to upload multiple files to the controller but its taking only one.
I am using multipart for file transfer.
How to get the multiple files to the controller side.
I am not able to access bytes and filename. Its throwing errors,
#RequestMapping(value = "/home/step38/uploadReport", method = RequestMethod.POST)
public ModelAndView uploadReport(
#RequestParam(value = "fileName") List<MultipartFile> files,
#RequestParam(value = "pLogId") String pLogId,
HttpServletRequest request, HttpSession session)
{
int applicationNameId = 0;
String fileName;
String typeOption = "Raw Particle Data";
for(MultipartFile file:files)
fileName = file.getOriginalFilename();
logger.debug("step3.1 upload particle count -- Start");
ModelAndView modelAndView = createModelAndView(ToogleStep.step38);
setCurrentStep(session, modelAndView, ToogleStep.step38);
String view = "redirect:/home/step38";
modelAndView.setViewName(view);
try
{
User user = (User) session.getAttribute(Constants.USER_DB);
Project current_project = (Project) session.getAttribute(Constants.PROJECT);
Credential credential = (Credential) session.getAttribute(Constants.AUTH_USER);
boolean checkOK = true;
if (current_project != null && SystemUtils.projectEditable(current_project, credential))
{
long projectId = current_project.getId();
if(checkOK)
{
byte[] bytes = file.getBytes();
HashMap<String,String> options= new HashMap<String,String>();
//added pLogId in the options(this will contain demoToogleFileInfoId)
options.put(ToogleReportDataConstants.TTL_PROCESS_LOG_ID_OPTION,pLogId);
String toogleFileId = reportService.uploadReport(user, projectId, fileName, typeOption, bytes, applicationNameId, options);
}
}
}
You are not looping through at the right location.
try looping it after you have your modelAndView(view)
int applicationNameId = 0;
String typeOption = "Raw Particle Data";
ModelAndView modelAndView = createModelAndView(ToogleStep.step38);
setCurrentStep(session, modelAndView, ToogleStep.step38);
String view = "redirect:/home/step38";
modelAndView.setViewName(view);
// upload multiple files.
for(MultipartFile file:files){
String fileName= file.getOriginalFilename();
and then you will be able to access bytes and filename. Give this a try.
Atleast by looking at your problem I can suggest and if you can give more specific error, I can help.
I want to send a file from my server side (EJB) using REST Jersey (JAX-RS).
I am trying with the following code,
Public Response getFiles() {
File file = new File(fileName);
FileOutputStream dest = new FileOutputStream(file);
ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(dest));
out.putNextEntry(new ZipEntry(fileName));
final ResponseBuilder response = Response.ok(out);
response.header("Content-Type", "*/*");
response.header("Content-Disposition", "attachment; filename=" + file.getName() + ".zip");
return response.build();
}
But I am getting the exception message
type class java.util.zip.ZipOutputStream, and MIME media type */* was not found
SEVERE: The registered message body writers compatible with the MIME media type are:
Also tried with "Content-Type" , "application/octet-stream", "application/x-www-form-urlencoded" and multipart/form-data
But none of them is working.
Use application/zip.
#GET
#Produces("application/zip")
public Response getZip() {
final File f = new File("/tmp/foo.zip");
ResponseBuilder response = Response.ok((Object) f);
response.header("Content-Disposition", "attachment; filename=" + f.getName());
return response.build();
}
application/octet-stream + gzip
#GET
#Path("/getFiles")
#Produces(MediaType.APPLICATION_OCTET_STREAM)
public Response getFiles() {
StreamingOutput stream = new StreamingOutput() {
#Override
public void write(OutputStream output) throws IOException, WebApplicationException {
String filePath = "/yourFile.pdf";
java.nio.file.Path path = Paths.get(filePath);
byte[] data = Files.readAllBytes(path);
output.write(data);
output.flush();
}
};
return Response.ok(stream).build();
}
and a jersey filter added to web.xml
<init-param>
<param-name>com.sun.jersey.spi.container.ContainerResponseFilters</param-name>
<param-value>com.sun.jersey.api.container.filter.GZIPContentEncodingFilter</param-value>
</init-param>
when making the request:
send a header of "Accept" with value of "application/octet-stream"
and a header of "Accept-Encoding" with value of "gzip"