我尝试了很多代码和示例,将文件上传到网页目录中名为files的web应用程序目录文件夹,但都没有这样做。我可以上传到C:/ upload文件夹,但是当我使用request.getContextPath
或getServletContext().getRealPath("")
时,它无法正常工作且没有错误或例外情况。事实上,我能够使用上面提到的方法之一从服务器中的文件夹中读取但无法在其上写入。这是我使用的最新代码而不能正常工作
public class test extends HttpServlet {
private final String UPLOAD_DIRECTORY ="files";
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
//String id = request.getParameter("icnumber");
if (ServletFileUpload.isMultipartContent(request)) {
try {
HttpSession session = request.getSession();
//String id = session.getAttribute("id").toString();
List<FileItem> multiparts = new ServletFileUpload(
new DiskFileItemFactory()).parseRequest(request);
for (FileItem item : multiparts) {
if (!item.isFormField()) {
String name = new File(item.getName()).getName();
//out.println(request.getContextPath().get+" gklg");
String link = getServletContext().getRealPath("")+File.separator+UPLOAD_DIRECTORY+File.separator+name;
out.println(link);
item.write(new File(link));
// if(updateDb(name, id))
out.println("<a href="+link+"> file</a> upload Successfully");
// else
out.println("something ewent wrong");
}
}
//File uploaded successfully
request.setAttribute("message", "File Uploaded Successfully");
} catch (Exception ex) {
request.setAttribute("message", "File Upload Failed due to " + ex);
}
} else {
request.setAttribute("message",
"Sorry this Servlet only handles file upload request");
}
}catch(Exception e){
out.println(e);
}
}