Howdy, Stranger!

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

Categories

Welcome to the new platform of Programmer's Heaven! We apologize for the inconvenience caused, if you visited us from a broken link of the previous version. The main reason to move to a new platform is to provide more effective and collaborative experience to you all. Please feel free to experience the new platform and use its exciting features. Contact us for any issue that you need to get clarified. We are more than happy to help you.

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.