Upload the file into the webapp folder - java

The user to upload the file with the txt extension to my system. I want this file to be accessible as www.exp.com/text_file.txt
But I could not do it.
Project/src/main/webapp/text_file.txt , If I drop the file under the webapp I can get it.
But how can I create txt file in webapp?
new File(---); --> this code does not what I want. It creates under the eclipse folder.
Project
->pom.xml
->src
->main
->java
->resources
->webapp
->WEB-INF

Assuming you are using servlets , this code should work (let's place file into webapp/resources)
public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException {
// Getting ServletContext from request
ServletContext ctx= req.getServletContext();
// Get the absolute path of the file
String filename = ctx.getRealPath("resources/file.text");
// getting mimeType of the file
String mime = ctx.getMimeType(filename);
// Error handling
if (mime == null) {
res.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
return;
}
// Setting MIME content type
res.setContentType(mime);
// Getting file object
File file = new File(filename);
// Setting content length header
res.setContentLength((int)file.length());
// FileInputStream to read from file
FileInputStream in = new FileInputStream(file);
// Obtain OutputStream from response object
OutputStream out = res.getOutputStream();
// Writing to the OutputStream
byte[] buffer = new byte[1024];
int bytes = 0;
// we stop when in.read returns -1 and read untill it does not
while ((bytes = in.read(buffer)) >= 0) {
out.write(buffer, 0, count);
}
// Clean up, closing resources
out.close();
in.close();
}

Related

How to set client side Folder path(Like D://new folder) for download file in spring contoller?

I have one spring controller, I want to download file in specific path like D:// or K://, But right now it will be download in downloads folder by default.
I am taking my file from /WEB-INF/ folder (server side located in Tomcat folder) and i want to write in client machine D:\ drive please see my below code is something wrong please let me know. I am using google crome.
Thanks in Advance
public void downloadFile(HttpServletRequest request,
HttpServletResponse response) throws IOException {
//ServletContext context = request.getServletContext();
String filePath = request.getSession().getServletContext().getRealPath("/WEB-INF/") + "/"+"out.json";
// get absolute path of the application
ServletContext context = request.getServletContext();
String appPath = context.getRealPath("");
System.out.println("appPath = " + appPath);
// construct the complete absolute path of the file
//String fullPath = appPath + filePath;
File downloadFile = new File(filePath);
FileInputStream inputStream = new FileInputStream(downloadFile);
// get MIME type of the file
String mimeType = context.getMimeType(filePath);
if (mimeType == null) {
// set to binary type if MIME mapping not found
mimeType = "application/octet-stream";
}
System.out.println("MIME type: " + mimeType);
// set content attributes for the response
response.setContentType(mimeType);
response.setContentLength((int) downloadFile.length());
// set headers for the response
String headerKey = "Content-Disposition";
String headerValue = String.format("attachment; filename=\"%s\"",
downloadFile.getName());
System.out.println("downloadFile.getName()" + downloadFile.getName());
response.setHeader(headerKey, headerValue);
// get output stream of the response
OutputStream outStream = response.getOutputStream();
byte[] buffer = new byte[BUFFER_SIZE];
int bytesRead = -1;
// write bytes read from the input stream into the output stream
while ((bytesRead = inputStream.read(buffer)) != -1) {
outStream.write(buffer, 0, bytesRead);
}
inputStream.close();
outStream.close();
}
You cannot decide where the client will save the downloaded file on server side - in fact, you cannot even affect whether it will save it anywhere at all! That's for the client (e.g. Chrome) to decide.
See Chrome help for how to change default download location in Chrome.

What should be the content type to download any file format in jsp?

I want to make a provision to download all file types...Is there any way to download any file format in jsp...
My code snippet:
String filename = (String) request.getAttribute("fileName");
response.setContentType("APPLICATION/OCTET-STREAM");
String disHeader = "Attachment";
response.setHeader("Content-Disposition", disHeader);
// transfer the file byte-by-byte to the response object
File fileToDownload = new File(filename);
response.setContentLength((int) fileToDownload.length());
FileInputStream fileInputStream = new FileInputStream(fileToDownload);
int i = 0;
while ((i = fileInputStream.read()) != -1) {
out.write(i);
}
fileInputStream.close();
If I specify setContentType as APPLICATION/OCTET-STREAM, pdf, text, doc files are getting downloaded.... But the problem is with image files...
What is problem with image files? I want to download all image file types...
I searched similar questions but could not find proper answer...
Thanks...
Finally I somehow managed to do this...
The problem is with JSP's "Out.write", which is not capable of writing byte stream...
I replaced jsp file with servlet...
The code snippet is:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
String filename = (String) request.getAttribute("fileName");
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition",
"attachment;filename="+filename);
File file = new File(filename);
FileInputStream fileIn = new FileInputStream(file);
ServletOutputStream out = response.getOutputStream();
byte[] outputByte = new byte[(int)file.length()];
//copy binary contect to output stream
while(fileIn.read(outputByte, 0, (int)file.length()) != -1)
{
out.write(outputByte, 0, (int)file.length());
}
}
Now I can download all types of files....
Thanks for the responces :)
Check the following link ,
JSP download - application/octet-stream
Might help you to resolve the issue.
for images you should use setContentType(image/jpg).you can checkout this link for mime types
http://webdesign.about.com/od/multimedia/a/mime-types-by-content-type.htm

Output an image file from a servlet [duplicate]

This question already has answers here:
Simplest way to serve static data from outside the application server in a Java web application
(10 answers)
Closed 6 years ago.
How to serve an image, stored on my hard drive, in a servlet?
For Example:
I have an image stored in path 'Images/button.png' and I want to serve this in a servlet with the URL file/button.png.
Here is the working code:
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
ServletContext cntx= req.getServletContext();
// Get the absolute path of the image
String filename = cntx.getRealPath("Images/button.png");
// retrieve mimeType dynamically
String mime = cntx.getMimeType(filename);
if (mime == null) {
resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
return;
}
resp.setContentType(mime);
File file = new File(filename);
resp.setContentLength((int)file.length());
FileInputStream in = new FileInputStream(file);
OutputStream out = resp.getOutputStream();
// Copy the contents of the file to the output stream
byte[] buf = new byte[1024];
int count = 0;
while ((count = in.read(buf)) >= 0) {
out.write(buf, 0, count);
}
out.close();
in.close();
}
map a servlet to the /file url-pattern
read the file from disk
write it to response.getOutputStream()
set the Content-Type header to image/png (if it is only pngs)
Here's another very simple way.
File file = new File("imageman.png");
BufferedImage image = ImageIO.read(file);
ImageIO.write(image, "PNG", resp.getOutputStream());

Create a file object from a resource path to an image in a jar file

I need to create a File object out of a file path to an image that is contained in a jar file after creating a jar file. If tried using:
URL url = getClass().getResource("/resources/images/image.jpg");
File imageFile = new File(url.toURI());
but it doesn't work. Does anyone know of another way to do it?
To create a file on Android from a resource or raw file I do this:
try{
InputStream inputStream = getResources().openRawResource(R.raw.some_file);
File tempFile = File.createTempFile("pre", "suf");
copyFile(inputStream, new FileOutputStream(tempFile));
// Now some_file is tempFile .. do what you like
} catch (IOException e) {
throw new RuntimeException("Can't create temp file ", e);
}
private void copyFile(InputStream in, OutputStream out) throws IOException {
byte[] buffer = new byte[1024];
int read;
while((read = in.read(buffer)) != -1){
out.write(buffer, 0, read);
}
}
Don't forget to close your streams etc
This should work.
String imgName = "/resources/images/image.jpg";
InputStream in = getClass().getResourceAsStream(imgName);
ImageIcon img = new ImageIcon(ImageIO.read(in));
Usually, you can't directly get a java.io.File object, since there is no physical file for an entry within a compressed archive. Either you live with a stream (which is best most in the cases, since every good API can work with streams) or you can create a temporary file:
URL imageResource = getClass().getResource("image.gif");
File imageFile = File.createTempFile(
FilenameUtils.getBaseName(imageResource.getFile()),
FilenameUtils.getExtension(imageResource.getFile()));
IOUtils.copy(imageResource.openStream(),
FileUtils.openOutputStream(imageFile));
You cannot create a File object to a reference inside an archive. If you absolutely need a File object, you will need to extract the file to a temporary location first. On the other hand, most good API's will also take an input stream instead, which you can get for a file in an archive.

Implementing a simple file download servlet [duplicate]

This question already has answers here:
Simplest way to serve static data from outside the application server in a Java web application
(10 answers)
Closed 2 years ago.
How should I implement simple file download servlet?
The idea is that with the GET request index.jsp?filename=file.txt, the user can download for example. file.txt from the file servlet and the file servlet would upload that file to user.
I am able to get the file, but how can I implement file download?
Assuming you have access to servlet as below
http://localhost:8080/myapp/download?id=7
I need to create a servlet and register it to web.xml
web.xml
<servlet>
<servlet-name>DownloadServlet</servlet-name>
<servlet-class>com.myapp.servlet.DownloadServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>DownloadServlet</servlet-name>
<url-pattern>/download</url-pattern>
</servlet-mapping>
DownloadServlet.java
public class DownloadServlet extends HttpServlet {
protected void doGet( HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String id = request.getParameter("id");
String fileName = "";
String fileType = "";
// Find this file id in database to get file name, and file type
// You must tell the browser the file type you are going to send
// for example application/pdf, text/plain, text/html, image/jpg
response.setContentType(fileType);
// Make sure to show the download dialog
response.setHeader("Content-disposition","attachment; filename=yourcustomfilename.pdf");
// Assume file name is retrieved from database
// For example D:\\file\\test.pdf
File my_file = new File(fileName);
// This should send the file to browser
OutputStream out = response.getOutputStream();
FileInputStream in = new FileInputStream(my_file);
byte[] buffer = new byte[4096];
int length;
while ((length = in.read(buffer)) > 0){
out.write(buffer, 0, length);
}
in.close();
out.flush();
}
}
That depends. If said file is publicly available via your HTTP server or servlet container you can simply redirect to via response.sendRedirect().
If it's not, you'll need to manually copy it to response output stream:
OutputStream out = response.getOutputStream();
FileInputStream in = new FileInputStream(my_file);
byte[] buffer = new byte[4096];
int length;
while ((length = in.read(buffer)) > 0){
out.write(buffer, 0, length);
}
in.close();
out.flush();
You'll need to handle the appropriate exceptions, of course.
Try with Resource
File file = new File("Foo.txt");
try (PrintStream ps = new PrintStream(file)) {
ps.println("Bar");
}
response.setContentType("application/octet-stream");
response.setContentLength((int) file.length());
response.setHeader( "Content-Disposition",
String.format("attachment; filename=\"%s\"", file.getName()));
OutputStream out = response.getOutputStream();
try (FileInputStream in = new FileInputStream(file)) {
byte[] buffer = new byte[4096];
int length;
while ((length = in.read(buffer)) > 0) {
out.write(buffer, 0, length);
}
}
out.flush();
The easiest way to implement the download is that you direct users to the file location, browsers will do that for you automatically.
You can easily achieve it through:
HttpServletResponse.sendRedirect()
And to send a largFile
byte[] pdfData = getPDFData();
String fileType = "";
res.setContentType("application/pdf");
httpRes.setContentType("application/.pdf");
httpRes.addHeader("Content-Disposition", "attachment; filename=IDCards.pdf");
httpRes.setStatus(HttpServletResponse.SC_OK);
OutputStream out = res.getOutputStream();
System.out.println(pdfData.length);
out.write(pdfData);
System.out.println("sendDone");
out.flush();

Categories