1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
|
public class FileUploadServlet extends HttpServlet {
private static final String UPLOAD_DIRECTORY = "d:\\uploaded\\";
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// TODO Auto-generated method stub
super.doGet(req, resp);
}
@SuppressWarnings("unchecked")
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
if (ServletFileUpload.isMultipartContent(req)) {
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
try {
List<FileItem> items = upload.parseRequest(req);
for (FileItem item : items) {
// process only file upload - discard other form item types
if (item.isFormField())
continue;
String fileName = item.getName();
if (fileName != null) {
fileName = FilenameUtils.getName(fileName);
}
File uploadedFile = new File(UPLOAD_DIRECTORY, fileName);
if (uploadedFile.createNewFile()) {
item.write(uploadedFile);
resp.setStatus(HttpServletResponse.SC_CREATED);
resp.getWriter().print("The file was created successfully.");
resp.flushBuffer();
} else {
throw new IOException("The file already exists in repository.");
}
}
} catch (Exception e) {
resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
"An error occurred while creating the file : " + e.getMessage());
}
} else {
resp.sendError(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE,
"Request contents type is not supported by the servlet.");
}
}
} |
Partager