Sample Java/Jsp Code to Upload a file - Programmers Heaven

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories

Sample Java/Jsp Code to Upload a file

rchuppalarchuppala Posts: 1Member
<%@ page contentType="text/html; charset=UTF-8" pageEncoding="ISO-8859-1" %>


File Upload Example











/*
* Created on Aug 29, 2009
*
* TODO To change the template for this generated file go to
* Window - Preferences - Java - Code Style - Code Templates
*/
package com.sample.upload;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
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.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

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

public void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {

try {

boolean isMultipart = ServletFileUpload.isMultipartContent(req);

if (isMultipart) {

ServletFileUpload servletFileUpload = new ServletFileUpload(
new DiskFileItemFactory());
List fileItemsList = servletFileUpload.parseRequest(req);

Iterator it = fileItemsList.iterator();

FileItem fileItem = (FileItem) it.next();

File uploadedFile = new File("a.txt");

fileItem.write(uploadedFile);

}
} catch (Exception ex) {
throw (new ServletException(ex));
}

}
}
Sign In or Register to comment.