I am reading servlet programming . While implementing ServletOutputStream for reading image from relative path it is throwing file not found exception .
I have tried multiple ways but failed , below is the snapshot of relevant code and folder structure in eclipse .
public void service(ServletRequest arg0, ServletResponse arg1)
throws ServletException, IOException {
arg1.setContentType("image/jpeg");
ServletOutputStream out = arg1.getOutputStream();
FileInputStream fis = new FileInputStream("images/myimage.jpg");
BufferedInputStream bin = new BufferedInputStream(fis);
BufferedOutputStream boit = new BufferedOutputStream(out);
int ch = 0;
while((ch = bin.read() ) != -1){
boit.write(ch);
}
boit.close();
bin.close();
fis.close();
out.close();
}
}
Get the ServletContext. Then get the resource as a stream.
final InputStream imageStream = arg0.getServletContext().getResourceAsStream("/images/myiamge.jpg");
Related
I should download a csv file from the server through browser.
I try with servlet with following code
private void writeFile(String filename, String content, HttpServletResponse response) throws IOException {
String filename="VR.csv";
try {
File file = new File(filename);
FileWriter fw = new FileWriter(file);
BufferedWriter bw = new BufferedWriter(fw);
bw.write(content);
bw.flush();
bw.close();
}
catch(IOException e) {
e.printStackTrace();
}
// This should send the file to browser
ServletOutputStream out = response.getOutputStream();
FileInputStream in = new FileInputStream(filename);
byte[] buffer = new byte[4096];
int length;
while ((length = in.read(buffer)) > 0){
out.write(buffer, 0, length);
}
in.close();
out.flush();
System.out.println("done");
}
But the program doesn't download any file in Download folder, program let me see in the browser the csv content. I need to have the VR.csv in the download folder of the browser.
You are not setting your response! If you want to download an specific file you need to specific in the response what type are you downloading and the path of the specific file.
response.setContentType("text/csv");
response.setHeader("Content-Disposition", "attachment;filename=yourFileName.csv");
In addition to previous answer, your method should have return type, like it should have ModelAndView if you use Spring Framework as follows
public ModelAndView writeFile(String filename, String content, HttpServletResponse response) throws IOException {}
I am using intellij Idea and I have saved my pdf file in resources folder. I want to display that pdf file in browser.
public class GetDocumentation extends HttpServlet {
private static final Logger log = Logger.getLogger(GetDocumentation.class);
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
InputStream pdf_path = this.getClass().getResourceAsStream(ApplicationProperties.getProperty("PDF_PATH"));
resp.setContentType("application/pdf");
resp.addHeader("Content-Disposition", "attachment; filename=Documentation.pdf");
OutputStream responseOutputStream = resp.getOutputStream();
byte[] buf = new byte[4096];
int len = -1;
while ((len = pdf_path.read(buf)) != -1) {
responseOutputStream.write(buf, 0, len);
}
responseOutputStream.flush();
responseOutputStream.close();
}
}
Documentation
I am using Jsp servlet and I am calling "/documentation". And my file is getting rendered but it's blank. Am I doing anything wrong?
inline Content-Disposition should be used to display the document. Replace "attachment" with "inline":
resp.addHeader("Content-Disposition", "inline; filename=Documentation.pdf");
I am a newbie in java and I want to display all the images from a system folder, viz. E://New
I am using a servlet but don't know how to proceed using it.
The servlet is:
response.setContentType("image/jpeg");
ServletOutputStream out;
out = response.getOutputStream();
FileInputStream fin = new FileInputStream("E:\\new\\");
BufferedInputStream bin = new BufferedInputStream(fin);
BufferedOutputStream bout = new BufferedOutputStream(out);
int ch = 0;
while((ch=bin.read())!=-1)
{
bout.write(ch);
}
bin.close();
fin.close();
bout.close();
out.close();
Thanks.
I think it can be made by this code
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
response.setContentType("image/jpeg");
String pathToWeb = getServletContext().getRealPath(File.separator);
File f = new File(pathToWebToyourfile);
BufferedImage bi = ImageIO.read(f);
OutputStream out = response.getOutputStream();
ImageIO.write(bi, "jpg", out);
out.close();
}
I have the below code got from mkyong, to zip files on local. But, my requirement is to zip files on server and need to download that. Could any one help.
code wrote to zipFiles:
public void zipFiles(File contentFile, File navFile)
{
byte[] buffer = new byte[1024];
try{
// i dont have idea on what to give here in fileoutputstream
FileOutputStream fos = new FileOutputStream("C:\\MyFile.zip");
ZipOutputStream zos = new ZipOutputStream(fos);
ZipEntry ze= new ZipEntry(contentFile.toString());
zos.putNextEntry(ze);
FileInputStream in = new FileInputStream(contentFile.toString());
int len;
while ((len = in.read(buffer)) > 0) {
zos.write(buffer, 0, len);
}
in.close();
zos.closeEntry();
//remember close it
zos.close();
System.out.println("Done");
}catch(IOException ex){
ex.printStackTrace();
}
}
what could i provide in fileoutputstream here? contentfile and navigationfile are files i created from code.
If your server is a servlet container, just write an HttpServlet which does the zipping and serving the file.
You can pass the output stream of the servlet response to the constructor of ZipOutputStream and the zip file will be sent as the servlet response:
ZipOutputStream zos = new ZipOutputStream(response.getOutputStream());
Don't forget to set the response mime type before zipping, e.g.:
response.setContentType("application/zip");
The whole picture:
public class DownloadServlet extends HttpServlet {
#Override
public void doGet( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException {
response.setContentType("application/zip");
response.setHeader("Content-Disposition", "attachment; filename=data.zip");
// You might also wanna disable caching the response
// here by setting other headers...
try ( ZipOutputStream zos = new ZipOutputStream(response.getOutputStream()) ) {
// Add zip entries you want to include in the zip file
}
}
}
Try this:
#RequestMapping(value="download", method=RequestMethod.GET)
public void getDownload(HttpServletResponse response) {
// Get your file stream from wherever.
InputStream myStream = someClass.returnFile();
// Set the content type and attachment header.
response.addHeader("Content-disposition", "attachment;filename=myfilename.txt");
response.setContentType("txt/plain");
// Copy the stream to the response's output stream.
IOUtils.copy(myStream, response.getOutputStream());
response.flushBuffer();
}
Reference
i have implemented a servlet to download doc files available under my application classpath.
what happening is; file is downloading but ms-word is unable to open it property.
see the screenshot of ms-word:
Servlet implementation is as follows:
public class DownloadFileServlet extends HttpServlet {
protected void doGet(
HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String fileName = "test.doc";
ClassPathResource resource = new ClassPathResource(File.separator + fileName);
ServletOutputStream sos = null;
FileInputStream fis = null;
try {
response.setContentType("application/msword");
response.setHeader("Content-disposition", "attachment; fileName=\"" + fileName + "\"" );
fis = new FileInputStream(new File(resource.getURI().getPath()));
byte[] bytes = org.apache.commons.io.IOUtils.toByteArray(fis);
sos = response.getOutputStream();
sos.write(bytes);
sos.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
if( fis != null) {
fis.close();
}
if( sos != null) {
sos.close();
}
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
i have tried almost all suggested Content Types for ms-word files. but still it is not working.
application/msword
application/ms-word
application/vnd.ms-word
Kindly suggest I'm making a mistake or is there any other way to achieve.
Note: i have tried almost all approaches available on SO.
Instead of reading, converting to byte[] simply write directly to the OutputStream. You shouldn't close the OutputStream as that is being handled by the container for you.
I would rewrite your servlet method to more or less the following (also why is it a servlet and not a (#)Controller?
protected void doGet(
HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String fileName = "test.doc";
ClassPathResource resource = new ClassPathResource(File.separator + fileName);
InputStream input = resource.getInputStream();
try {
response.setContentType("application/msword");
response.setHeader("Content-disposition", "attachment; fileName=\"" + fileName + "\"" );
org.springframework.util.StreamUtils.copy(input, response.getOutputStream());
} catch (Exception e) {
e.printStackTrace();
} finally {
if (input != null) {
try {
input.close();
} catch (IOEXception ie) {}
}
}
}
i do not know what a ClassPathResource class does. hence modified the code a bit.
ClassLoader clsLoader = Thread.currentThread().getContextClassLoader();
InputStream is = clsLoader.getResourceAsStream("test.doc");
and in the try block use:
byte[] bytes = org.apache.commons.io.IOUtils.toByteArray(is);
this should work fine. i placed the doc in the classpath. modify it to suit your needs.
Regarding the mime mapping, open your server properties and you will find a list of mime mapping. Eg. in eclipse for tomcat, just double click on the server and you should be able to find the mime mapping list there. application/msword worked fine