Java Reference
In-Depth Information
Upload
-----------------------------263081694432439--
The servlet
FileUploadServlet.java
can be found in the
tut-install
/examples/
web/fileupload/src/java/fileupload/
directory. The servlet begins as fol-
lows:
@WebServlet(name = "FileUploadServlet", urlPatterns = {"/upload"})
@MultipartConfig
public class FileUploadServlet extends HttpServlet {
private final static Logger LOGGER =
Log-
ger.getLogger(FileUploadServlet.class.getCanonicalName());
The
@WebServlet
annotation uses the
urlPatterns
property to define servlet map-
pings.
The
@MultipartConfig
annotation indicates that the servlet expects requests to made
using the
multipart/form-data
MIME type.
The
processRequest
method retrieves the destination and file part from the request,
then calls the
getFileName
method to retrieve the file name from the file part. The
method then creates a
FileOutputStream
and copies the file to the specified des-
tination. The error-handling section of the method catches and handles some of the
most common reasons why a file would not be found. The
processRequest
and
getFileName
methods look like this:
protected void processRequest(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
// Create path components to save the file
final String path = request.getParameter("destination");
final Part filePart = request.getPart("file");
final String fileName = getFileName(filePart);
OutputStream out = null;
InputStream filecontent = null;
final PrintWriter writer = response.getWriter();