Sat Jun 09, 2007 12:07 pm
Here the code that you can use it to upload a files using servlets
[code=java5]package com.servlet;
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException ;
import java.util.List;
import javax.servlet. RequestDispatcher;
import javax.servlet. ServletContext;
import javax.servlet. ServletException ;
import javax.servlet. ServletInputStream;
import javax.servlet. ServletOutputStream;
import javax.servlet. http.HttpServlet ;
import javax.servlet. http.HttpServletRequest;
import javax.servlet. http.HttpServletResponse;
import org.apache.commons. fileupload.FileItem;
import org.apache.commons. fileupload.disk.DiskFileItemFactory;
import org.apache.commons. fileupload.portlet.PortletFileUpload;
import org.apache.commons. fileupload.servlet.ServletFileUpload;
import org.apache.struts. upload.FormFile;
import com.oreilly. servlet.MultipartRequest;
import com.oreilly. servlet.multipart.MultipartParse r;
public class uploadFile extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = 6807130476935151822 L;
public void service (HttpServletRequest req, HttpServletResponse res)
throws IOException , ServletException
{
System.out.println( " :in upload File :");
doPost(req,res) ;
}
public void doPost(HttpServletRequest req, HttpServletResponse res)
{
System.out.println( " :in do post upload File :");
String message="";
try{
MultipartRequest mr=new MultipartRequest( req,"c:\\ testUpload" );
// MultipartParser mp=new MultipartParser( );
if (ServletFileUpload. isMultipartConte nt(req)){
ServletFileUpload servletFileUpload = new ServletFileUpload( new
DiskFileItemFactory ());
List fileItemsList = servletFileUpload.parseRequest( req);
for(FileItem fi : fileItemsList)
{ System.out.println( "uploaded file name " + fi.getName() );
byte fileByteData []=fi.get();
ByteArrayOutputStre am baos = new ByteArrayOutputStre am();
System.out.println( "File Name : " +
fi.getName() .substring( fi.getName( ).lastIndexOf( "\\")+1)) ;
FileOutputStream fileOut=new FileOutputStream( "c:\\"+
fi.getName() .substring( fi.getName( ).lastIndexOf( "\\")+1)) ;
byte[] array = fi.get();
for (int cnt = 0; cnt e= req.getParameterNam es();
System.out.println( "Request Parameters : " );
try{
ServletInputStream is= req.getInputStream( );
Object o=req.getParameter( "file");
System.out.println( o.getClass( ).toString( ));
}catch(Exception ex)
{
System.out.println( "EX : " + ex.getMessage( ));
}
while(e.hasMoreElem ents())
{
System.out.println( e.nextElement( ));
}*/
}
}[/code]
Codemiles.com is a participant in the Amazon Services LLC Associates Program, an affiliate advertising program designed to provide a means for sites to earn advertising fees by advertising and linking to Amazon.com
Powered by phpBB © phpBB Group.