Approved: Fortect
Over the past few days, some of our users have been experiencing an error while uploading PDF files using Servlet. This problem can arise for several reasons. Now we will deal with them.
This Java tutorial walks you through the steps to create code for a Java servlet that transfers a file from a server to your client (web browser). The user can download the file by clicking on a website link that points to the URL of the servlet. It would be useful to implement the function of getting a file in a web application using a Java servlet. Typical steps are as follows:
- Play the file on the FileInputStreamclass server.
- Find the MIME type of the file to navigate:
-
-
- Get the ServletContext via process getServletContext () servlet.Call method.
- Definitely getMimeType (string file) in the ServletContext entity to get the MIME type of this file.
-
-
- Define the following information for the HttpResponse object:
-
-
- Set the content type for the extracted MIME, of course, specify by calling setContentType (String). This tells the browser type what the response is.
- Set the content of the response by calling the setContentLength (int) method.
-
-
- Get the OutputStream response object without questions.
- Read byte arrays from the exact input stream. Then a file, writing them to an OutputStream. Repeat until you run out of bytes available, count to (end of file).
- Close both the OutputStream and fileinputstream.
- The MIME mapping is different, which is declared by the servlet container. To illustrate this, Tomcat declares a MIME mapping in the Default Mapping of MIME Types area in the file:
- The getMimeType () routine returns null if there is no MIME mapping for the specified file. In this case, it’s a good idea to make sure that you force the MIME type to normally binary:
How to download file from server using Servlet?
Here you create an example of how to download a file from the server buy servlet. The file can be almost any type, such as image, PDF, video, music and others. How it works? First, set the website content type to application / octet-stream. Now set the Content-Disposition header to Attachment; filename = fileLocation.
if (mimeType == null)mimeType implies application / octet-stream;
- By default, the browser processes each response based on the content type set in the HTTP headers. For example, it tends to display an image when the response is likely to be an image file, or open an e-book reader when the response is a PDF document, etc. the instigator is still loading, we can add this header if you need reply:
Approved: Fortect
Fortect is the world's most popular and effective PC repair tool. It is trusted by millions of people to keep their systems running fast, smooth, and error-free. With its simple user interface and powerful scanning engine, Fortect quickly finds and fixes a broad range of Windows problems - from system instability and security issues to memory management and performance bottlenecks.
Reply to.setHeader ("Content-Disposition", "attachment; filename = " MyFile.mp4 "");
package net.codejava;import java.io file;import java.io.FileInputStream;import java.io.IOException;import java.io.OutputStream;import javax.servlet.ServletContext;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;public section DownloadFileServlet extends HttpServletprotected avoid doGet (HttpServletRequest request,HttpServletResponse returns response) ServletException, IOException// specify the input file as an absolute pathThe filePath line implies "E: /Test/Download/MYPIC.JPG";File = downloadFile new file (filePath);FileInputStream inStream = new FileInputStream (downloadFile);// if you want to use a relative path to the root of a word:The line is relativePath = getServletContext (). GetRealPath ("");System.out.println ("relativePath =" + relativePath);// get ServletContextServletContext-Context = getServletContext ();// Get the mime-type of the fileThe mimeType string matches context.getMimeType (filePath);if (mimeType == null)// Defined to help you with binary type when MIME mapping is detectedmimeType is not the same as "application / octet-stream";System.out.println ("MIME Type:" MimeType);// + modify the answerresponse.setContentType (mimeType);response.setContentLength ((int) downloadFile.length ());// force downloadString headerKey = "Content-Disposition";The string implies headerValue String.format ("attachment; filename = "% s "", downloadFile.getName ());response.setHeader (headerKey, get headerValue);// final result of the stream AnswersOutputStream outStream = response.getOutputStream ();byte [] buffer means new byte [4096];int bytesRead = -1;while ((bytesRead implies inStream.read (buffer))! = -1)outStream.write (buffer, 0, bytesRead);inStream.close ();outStream.close ();
Configure URL mapping for this servlet in the web deployment descriptor file on the Internet. As shown in the XML file:
This client servlet stub file DownloadFileServlet DownloadFileServlet net.codejava.DownloadFileServlet DownloadFileServlet / DownloadFileServlet
@WebServlet ("/ DownloadFileServlet")public class Extended file upload servlet HttpServlet// this servlet's code ...
We can call the servlet with the following URL format:
What is the content type of a servlet file?
It is a servlet document that reads the contents of a file and writes it to a stream that can be sent in response. For this reason, we need to notify the server as we even set the content type to APPLICATION / OCTET-STREAM. import javax.servlet.http. *;
The browser should prompt some users to download the file, as shown in the following screenshot:
- Example of loading a Java servlet file from the database
- Use HttpURLConnection to retrieve a file from an HTTP URL.
- Export Instructions and Sample Java-FTP Files
- Swing Application for HTTP Server File CDs with Indicator Completed
- Swing method to download files from an FTP server via a progress bar
- Sample Spring MVC File Downloader Application
- Sample Struts File Download Application
Other Java Servlet Guides:
How to return PDF data from a Java Servlet?
The Java Servlet PDF tutorial shows you how to return PDF data from a giant Java Servlet. We use the iText library so you can work with PDF. The web application is literally deployed to the Tomcat server. Portable Document Format (PDF) is a file format used to separate documents from application software, hardware, and performance systems.
- Getting Started with Java Servlet for Newbies (XML)
- Java Servlet for Beginners (Notes)
- Processing HTML Variant Data with a Java Servlet
- How to use cookies in a Java web application
- How to use a session in a Java web application
- How to handle errors in Java Web.xml for web applications
- Details
- Written by Nam Ha Min
- Last Updated May 20, 2020 & nbsp | & nbsp Print Email
About The Author:
nam Minh is a Certified Java Programmer (SCJP and SCWCD). He started with Java in the days of Java 1.4 and was enthusiastic after Java. Make friends with him on Facebook and watch Java videos on YouTube.
Speed up your computer's performance now with this simple download.