How to upload a file using servlet

Questions by sunmyid

Showing Answers 1 - 1 of 1 Answers

Rajesh

  • Oct 24th, 2005
 

<html>
<form method="post" action="/uploadFile" enctype="multipart/form-data">
Name
<input type="text" name="uname"/>
File
<input type="file" name="upfile"/>
<input type="submit"/>
</form>

</html>



---------------------------My servlet---------------------------
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.DiskFileUpload;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUpload;
import org.apache.commons.fileupload.FileUploadException;


/**
* @author sm23772
*
* TODO To change the template for this generated type comment go to
* Window - Preferences - Java - Code Style - Code Templates
*/
public class UploadFile extends HttpServlet {

public void doPost(HttpServletRequest req,HttpServletResponse res)
{
try{

FileUpload fup=new FileUpload();
boolean isMultipart = FileUpload.isMultipartContent(req);
// Create a new file upload handler
System.out.println(isMultipart);
DiskFileUpload upload = new DiskFileUpload();

// Parse the request
List /* FileItem */ items = upload.parseRequest(req);

Iterator iter = items.iterator();
while (iter.hasNext()) {

FileItem item = (FileItem) iter.next();

if (item.isFormField()) {
System.out.println("its a field");
} else {
System.out.println("its a file");
System.out.println(item.getName());
File cfile=new File(item.getName());
File tosave=new File(getServletContext().getRealPath("/"),cfile.getName());
item.write(tosave);
}
}

}catch(Exception e){System.out.println(e);}
}
}

  Was this answer useful?  Yes

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

 

Related Answered Questions

 

Related Open Questions