日期:2014-05-18  浏览次数:20616 次

commons-upload如何上传到目录?
请问怎样用COMMONS-UPLOAD编写SERLVET   上传文件到WEB   服务器的目录呢~?
像以下的这样,如何做到上传到WEB   服务器的根目录呢
javax.servlet.http.HttpServlet#doGet(HttpServletRequest   request,   HttpServletResponse   response)
  */
protected   void   doGet(HttpServletRequest   request,   HttpServletResponse   response)   throws   ServletException,   IOException   {
//   TODO   Auto-generated   method   stub
}    

/*   (non-Java-doc)
  *   @see   javax.servlet.http.HttpServlet#doPost(HttpServletRequest   request,   HttpServletResponse   response)
  */
protected   void   doPost(HttpServletRequest   request,   HttpServletResponse   response)   throws   ServletException,   IOException   {
//   TODO   Auto-generated   method   stub
try{
request.setCharacterEncoding( "gb2312 ");
String   path=request.getContextPath();
if(ServletFileUpload.isMultipartContent(request)){
ServletFileUpload   upload=new   ServletFileUpload();
FileItemIterator   iter=upload.getItemIterator(request);

while(iter.hasNext()){
FileItemStream   item=iter.next();
String   name=item.getFieldName();
InputStream   stream=item.openStream();
if(item.isFormField()){
response.getWriter().print( "File   filed ");
}else
{
String   filename=new   File(item.getName()).getName();
response.getWriter().print( "File   filed: "+filename);
BufferedInputStream   bis=new   BufferedInputStream(stream);
BufferedOutputStream   bos=new   BufferedOutputStream(new   FileOutputStream(new   File( "\\upload\\ "+filename)));
Streams.copy(bis,   bos,   true);


}
}
}



}catch(Exception   e){
response.getWriter().print(e.toString());

}

}                  
}

------解决方案--------------------
例:http://localhost:8080/webApp
String host = request.getHeader( "host ");
host:(localhost:8080)
String path = request.getContextPath();
path:(/webApp)

File newFile = new File( "http:// "+host+path + fullFile.getName());
fileItem.write(newFile);