File uploading in jsp

this is rambabu,
i am new to fileuploading concepts. any body help me how to upload a file .please send me the code to mail.my mail id is
[email protected]

Jakarta Commons File Upload.
search, read, use.
and FYI... posting your email address is a sure-fire way to get yourself on more spam mailing lists, but hey.. maybe you like spam.

Similar Messages

  • File upload with jsp

    I am trying to upload a file to a mysql database (using a jsp tomcat 4.1 container) for each new member of my website (typically a cv which is a .rtf word file). I have used the example on the oreilly page and have managed to get the image of the file I have uploaded. Now I am trying to save this into my database for each member so that they can enter all of their details on the one page i.e. name age etc and also a browse for file button which will store the path of their file on their computer. When they click the submit button, all of their details are then stored into the database by the resultant page which outputs wehter they have been successful or not.
    The upload bean code (from the oreilly site):
    package com.idhcitip;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.ServletInputStream;
    import java.util.Dictionary;
    import java.util.Hashtable;
    import java.io.PrintWriter;
    import java.io.BufferedWriter;
    import java.io.FileWriter;
    import java.io.IOException;
    public class FileUploadBean {
    private String savePath, filepath, filename, contentType;
    private Dictionary fields;
    public String getFilename() {
    return filename;
    public String getFilepath() {
    return filepath;
    public void setSavePath(String savePath) {
    this.savePath = savePath;
    public String getContentType() {
    return contentType;
    public String getFieldValue(String fieldName) {
    if (fields == null || fieldName == null)
    return null;
    return (String) fields.get(fieldName);
    private void setFilename(String s) {
    if (s==null)
    return;
    int pos = s.indexOf("filename=\"");
    if (pos != -1) {
    filepath = s.substring(pos+10, s.length()-1);
    // Windows browsers include the full path on the client
    // But Linux/Unix and Mac browsers only send the filename
    // test if this is from a Windows browser
    pos = filepath.lastIndexOf("\\");
    if (pos != -1)
    filename = filepath.substring(pos + 1);
    else
    filename = filepath;
    private void setContentType(String s) {
    if (s==null)
    return;
    int pos = s.indexOf(": ");
    if (pos != -1)
    contentType = s.substring(pos+2, s.length());
    public void doUpload(HttpServletRequest request) throws IOException {
    ServletInputStream in = request.getInputStream();
    byte[] line = new byte[128];
    int i = in.readLine(line, 0, 128);
    if (i < 3)
    return;
    int boundaryLength = i - 2;
    String boundary = new String(line, 0, boundaryLength); //-2 discards the newline character
    fields = new Hashtable();
    while (i != -1) {
    String newLine = new String(line, 0, i);
    if (newLine.startsWith("Content-Disposition: form-data; name=\"")) {
    if (newLine.indexOf("filename=\"") != -1) {
    setFilename(new String(line, 0, i-2));
    if (filename==null)
    return;
    //this is the file content
    i = in.readLine(line, 0, 128);
    setContentType(new String(line, 0, i-2));
    i = in.readLine(line, 0, 128);
    // blank line
    i = in.readLine(line, 0, 128);
    newLine = new String(line, 0, i);
    PrintWriter pw = new PrintWriter(new BufferedWriter(new
    FileWriter((savePath==null? "" : savePath) + filename)));
    while (i != -1 && !newLine.startsWith(boundary)) {
    // the problem is the last line of the file content
    // contains the new line character.
    // So, we need to check if the current line is
    // the last line.
    i = in.readLine(line, 0, 128);
    if ((i==boundaryLength+2 || i==boundaryLength+4) // + 4 is eof
    && (new String(line, 0, i).startsWith(boundary)))
    pw.print(newLine.substring(0, newLine.length()-2));
    else
    pw.print(newLine);
    newLine = new String(line, 0, i);
    pw.close();
    else {
    //this is a field
    // get the field name
    int pos = newLine.indexOf("name=\"");
    String fieldName = newLine.substring(pos+6, newLine.length()-3);
    //System.out.println("fieldName:" + fieldName);
    // blank line
    i = in.readLine(line, 0, 128);
    i = in.readLine(line, 0, 128);
    newLine = new String(line, 0, i);
    StringBuffer fieldValue = new StringBuffer(128);
    while (i != -1 && !newLine.startsWith(boundary)) {
    // The last line of the field
    // contains the new line character.
    // So, we need to check if the current line is
    // the last line.
    i = in.readLine(line, 0, 128);
    if ((i==boundaryLength+2 || i==boundaryLength+4) // + 4 is eof
    && (new String(line, 0, i).startsWith(boundary)))
    fieldValue.append(newLine.substring(0, newLine.length()-2));
    else
    fieldValue.append(newLine);
    newLine = new String(line, 0, i);
    //System.out.println("fieldValue:" + fieldValue.toString());
    fields.put(fieldName, fieldValue.toString());
    i = in.readLine(line, 0, 128);
    } // end while
    This works fine and I can access the image name of the file by using the commands in my jsp code(on the resultant page of the new member form):
    <%@ page import="java.sql.*, com.idhcitip.*"%>
    <jsp:useBean id="TheBean" scope="page" class="com.idhcitip.FileUploadBean" />
    <%
    TheBean.doUpload(request);
    out.println("Filename:" + TheBean.getFilename());
    So I am wondering how can I then store this image into a text blob in the database?
    I found some code on the java.sun forum, but am not entirely sure how I am meant to use it?
    package com.idhcitip;
    import java.sql.*;
    import java.io.*;
    class BlobTest {
    public static void main(String args[]) {
    try {
    //File to be created. Original file is duke.gif.
    //DriverManager.registerDriver( new org.gjt.mm.mysql.Driver());
    Class.forName("org.gjt.mm.mysql.Driver").newInstance();
    String host="localhost";
    String user="root";
    String pass="";
    String db="idhcitip";
    String conn;
    // create connection string
    conn = "jdbc:mysql://" + host + "/" + db + "?user=" + user + "&password=" +
    pass;
    // pass database parameters to JDBC driver
    Connection Conn = DriverManager.getConnection(conn);
    // query statement
    Statement SQLStatement = Conn.createStatement();
    /*PreparedStatement pstmt = conn.prepareStatement("INSERT INTO BlobTest VALUES( ?, ? )" );
    pstmt.setString( 1, "photo1");
    File imageFile = new File("duke.gif");
    InputStream is = new FileInputStream(imageFile);
    pstmt.setBinaryStream( 2, is, (int)(imageFile.length()));
    pstmt.executeUpdate();
    PreparedStatement pstmt = Conn.prepareStatement("SELECT image FROM testblob WHERE Name = ?");
    pstmt.setString(1, args[0]);
    RandomAccessFile raf = new RandomAccessFile(args[0],"rw");
    ResultSet rs = pstmt.executeQuery();
    if(rs.next()) {
    Blob blob = rs.getBlob(1);
    int length = (int)blob.length();
    byte [] _blob = blob.getBytes(1, length);
    raf.write(_blob);
    System.out.println("Completed...");
    } catch(Exception e) {
    System.out.println(e);
    Once I have managed to store the file, I would just like people to be able to view each members profile and then to click on a link that will have their stored c.v.
    Thanks for a reply anyone

    You could do this one of two ways..
    using a prepaired statment, you could read in a byte array...
    String sql="INSERT INTO BlobTest VALUES( ? )";
    PreparedStatement ps=con.prepareStatement(sql);
    ps.setBytes(1, byte[]); //Your byte array buffer from your FileUploadBean
    ps.executeUpdate();or you could just use the input stream..
    String sql="INSERT INTO BlobTest VALUES( ? )";
    PreparedStatement ps=con.prepareStatement(sql);
    ps.setBinaryStream(1, InputStream, length); //You'll have to do some work to get length
    ps.executeUpdate();

  • Error in File uploading using jsp

    I am tring to upload files to a mysql database using jsp.I have used BLOB type to store files.Iam using the JDBC driver mysql-connector-java-2.0-14-bin to connect the database with the jsp API.My problem is when i try to transfer a file of size which is less than the possible capacity through blob ,which is 1048576 bytes ( for example when a file of size 916KB is attempted to transfer) the following error is being generated.
    java.lang.IllegalArgumentException: Packet is larger than max_allowed_packet from server configuration of 1048576 bytes
         at com.mysql.jdbc.Buffer.ensureCapacity(Unknown Source)
         at com.mysql.jdbc.Buffer.writeBytesNoNull(Unknown Source)
         at com.mysql.jdbc.PreparedStatement.executeUpdate(Unknown Source)
         at com.mysql.jdbc.PreparedStatement.executeUpdate(Unknown Source)
         at org.apache.jsp.file3$jsp._jspService(file3$jsp.java:110)
         at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:107)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
         at org.apache.jasper.servlet.JspServlet$JspServletWrapper.service(JspServlet.java:201)
         at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:381)
         at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:473)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
         at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:247)
         at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:193)
         at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:243)
         at org.apache.catalina.core.StandardPipeline.invokeNext(StandardPipeline.java:566)
         at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:472)
         at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:943)
         at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:190)
         at org.apache.catalina.core.StandardPipeline.invokeNext(StandardPipeline.java:566)
         at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:475)
         at org.apache.catalina.core.StandardPipeline.invokeNext(StandardPipeline.java:564)
         at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:472)
         at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:943)
         at org.apache.catalina.core.StandardContext.invoke(StandardContext.java:2347)
         at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:180)
         at org.apache.catalina.core.StandardPipeline.invokeNext(StandardPipeline.java:566)
         at org.apache.catalina.valves.ErrorDispatcherValve.invoke(ErrorDispatcherValve.java:170)
         at org.apache.catalina.core.StandardPipeline.invokeNext(StandardPipeline.java:564)
         at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:170)
         at org.apache.catalina.core.StandardPipeline.invokeNext(StandardPipeline.java:564)
         at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:468)
         at org.apache.catalina.core.StandardPipeline.invokeNext(StandardPipeline.java:564)
         at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:472)
         at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:943)
         at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:174)
         at org.apache.catalina.core.StandardPipeline.invokeNext(StandardPipeline.java:566)
         at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:472)
         at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:943)
         at org.apache.catalina.connector.http.HttpProcessor.process(HttpProcessor.java:1027)
         at org.apache.catalina.connector.http.HttpProcessor.run(HttpProcessor.java:1125)
         at java.lang.Thread.run(Thread.java:484)
    java.lang.IllegalArgumentException: Packet is larger than max_allowed_packet from server configuration of 1048576 bytes
         at com.mysql.jdbc.Buffer.ensureCapacity(Unknown Source)
         at com.mysql.jdbc.Buffer.writeBytesNoNull(Unknown Source)
         at com.mysql.jdbc.PreparedStatement.executeUpdate(Unknown Source)
         at com.mysql.jdbc.PreparedStatement.executeUpdate(Unknown Source)
         at org.apache.jsp.file3$jsp._jspService(file3$jsp.java:110)
         at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:107)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
         at org.apache.jasper.servlet.JspServlet$JspServletWrapper.service(JspServlet.java:201)
         at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:381)
         at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:473)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
         at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:247)
         at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:193)
         at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:243)
         at org.apache.catalina.core.StandardPipeline.invokeNext(StandardPipeline.java:566)
         at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:472)
         at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:943)
         at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:190)
         at org.apache.catalina.core.StandardPipeline.invokeNext(StandardPipeline.java:566)
         at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:475)
         at org.apache.catalina.core.StandardPipeline.invokeNext(StandardPipeline.java:564)
         at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:472)
         at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:943)
         at org.apache.catalina.core.StandardContext.invoke(StandardContext.java:2347)
         at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:180)
         at org.apache.catalina.core.StandardPipeline.invokeNext(StandardPipeline.java:566)
         at org.apache.catalina.valves.ErrorDispatcherValve.invoke(ErrorDispatcherValve.java:170)
         at org.apache.catalina.core.StandardPipeline.invokeNext(StandardPipeline.java:564)
         at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:170)
         at org.apache.catalina.core.StandardPipeline.invokeNext(StandardPipeline.java:564)
         at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:468)
         at org.apache.catalina.core.StandardPipeline.invokeNext(StandardPipeline.java:564)
         at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:472)
         at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:943)
         at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:174)
         at org.apache.catalina.core.StandardPipeline.invokeNext(StandardPipeline.java:566)
         at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:472)
         at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:943)
         at org.apache.catalina.connector.http.HttpProcessor.process(HttpProcessor.java:1027)
         at org.apache.catalina.connector.http.HttpProcessor.run(HttpProcessor.java:1125)
         at java.lang.Thread.run(Thread.java:484)
    My uploading code in jsp is as follows.
         <% try{
              Class.forName("org.gjt.mm.mysql.Driver").newInstance();
              Connection dbCon = DriverManager.getConnection("jdbc:mysql:///uoc");
              out.println("Connection done !");
              Statement stmt = dbCon.createStatement();
              out.println("Statement Created !");
    ResultSet rs = stmt.executeQuery("SELECT * FROM blob_test)
    stmt.close();
    dbCon.close();
    out.println("<br><br> <b>Data Successfully selected !<b>");
    } //try
    catch(SQLException e){
         out.println(" <br> ");
         out.println("Sorry ! problem in selecting a data "+e.toString());
         out.println(" <br> ");
                   e.printStackTrace();
    %>
    Please help .I thank You in advance for any help .

    Have you tried increasing the BLOB field greater than 1048576 or using a smaller file of say 1 or 2k as a test? There is no guarantee that the database will store the file with exactly the same size as the file on the filesystem, so the file might be more than 916k in the database.
    Using BLOBs is a great way to destroy the performance of your database by the way :)

  • Multiple file upload in jsp with out using �FILE� type filed.

    I have an applet that is used for multiple file selection, It allows drag and drop functionality also. The problem is once the user selects multiple files it has to get uploaded to the server. Since it�s not part of a file type component while submitting the form we won�t get the file contents.
    We can use multipart api for uploading files, but if the file selected by the user is not by the file type filed the file contents won�t come as part in the jsp submission and I can�t assign the file names selected by the user through the applet to any FILE (hidden ) type in jsp .
    Please give a solution�

    We can use multipart api for uploading files, but if the file selected by the user is not by the file type filed the file contents won&#146;t come as part in the jsp submission and I can&#146;t assign the file names selected by the user through the applet to any FILE (hidden ) type in jsp .Well i think thats a wrong notion which you have...
    you can very well get non-file type field data & file item data from a multipart form.
    Anyways,Letz checkout a simple example(refer to the below Code-snippet down below) which can do that task for us and it uses commons-fileupload & commons-io libraries.
    FileUpload.jsp
    ==========
    <form name="sampleForm" action="uploadAction" method="POST" enctype="multipart/form-data">
      File Name 1: <input type="text" name="fileName1" size="5" /> <br/>
      File: <input type="file" name="file1" id="file1" /> <br/>
      File Name 2: <input type="text" name="fileName2" size="5" /> <br/>
      File: <input type="file" name="file2" id="file2" /> <br/>
      File Name 3: <input type="text" name="fileName3" size="5" /> <br/>
      File: <input type="file" name="file3" id="file3"/> <br/>
      File Name 4: <input type="text" name="fileName4" size="5" /> <br/>
      File: <input type="file" name="file4" id="file4"/> <br/>
      <input type="submit" value="upload"/>
    </form>uploadAction method in (backingBean) :
    ==============================
    public void uploadAction(HttpServletRequest request,HttpServletResponse response)throws Exception{
          FileUploadUtils fuu = new FileUploadUtils(request);
          Map<String,FileItem> fileFields = fuu.getFileFiledsMap();
          Map<String,String> nonfileFields = fuu.getNonFileFiledsMap();
           String fileName1 =  nonfileFields.get("fileName1");
           FileItem file1 = fileFields.get("file1");       
           byte file1ContentBuffer[] = file1.get();
           String file1ContentType = file1.getContentType();
           InputStream file1ins = file1.getInputStream(); 
           file1.write(file1Name);
           String fileName2 =  nonfileFields.get("fileName2");
           FileItem file2 = fileFields.get("file2");
           byte file2ContentBuffer[] = file2.get();
           String file2ContentType = file2.getContentType();
           InputStream file2ins = file2.getInputStream();
           file2.write(file2Name);
    }FileUploadUtils.java:
    ===============
    import java.io.File;
    import java.io.FileOutputStream;
    import java.util.ArrayList;
    import java.util.Date;
    import java.util.Iterator;
    import java.util.List;
    import java.util.StringTokenizer;
    import java.util.Vector;
    import javax.servlet.http.HttpServletRequest;
    import org.apache.commons.fileupload.DiskFileUpload;
    import org.apache.commons.fileupload.FileItem;
    import com.gehcsr.utils.dao.DbQueryUtils;
    public class FileUploadUtils {
       private Map<String,FileItem> fileItemMap = null;
       private  Map<String,String> nFileItemMap = null;
       private HttpServletRequest request = null;
       public FileUploadUtils(HttpServletRequest request)throws Exception{
                   this.request = request;    
                   this.fileItemMap = new HashMap<String,FileItem>();
                   this.nFileItemMap = new HashMap<String,String>();
                   this.init();
       private void init() throws Exception{
          DiskFileUpload dfu  = null;
          List fileItems  = null;   
             try{
                   dfu = new DiskFileUpload();
                   dfu.setSizeMax(1000000);
                   dfu.setSizeThreshold(4096);
                   dfu.setRepositoryPath(System.getProperty(java.io.tmpdir));
                   fileItems = dfu.parseRequest(this.request);
                   if(dfu.isMultipartContent && fileItems != null){
                            Iterator iter =  fileItems.iterator();
                  while (iter.hasNext()) {
                       FileItem item = (FileItem) iter.next();           
                                  String fieldName = item.getFieldName(); 
                             if (!item.isFormField()){
                                              String fieldValue = item.toString();
                                               this.nFileItemMap.put(fieldName,fieldName); 
                                         }else
                                             this.fileItemMap.put(fieldName,item);                              
                    }catch(Exception exp){
                         exp.printStackTrace();
                         System.err.println(exp.getMessage());
                         throw new Exception(exp.getCause());
                    } finally{
                       fileItems = null;
                       dfu = null; 
             public  Map<String,FileItem>  getFileFiledsMap(){
                    return this.getFileFiledsMap;
             public Map<String,String> getNonFileFiledsMap(){
                   return this.nFileItemMap;
    NOTE:* Do not forget to add latest versions of commons-fileupload.jar & commons-io.jar in your classpath.You might get few warings due some issues with regards to generics please neglect them.
    and it is not certain that you ought to use commons libraries for this there are many other alternative solutions available by which you can implement a similar functionality.
    Hope this might help !!! if that does do not forget to assign/share duke dollars which you have promised :)
    REGARDS,
    RaHuL

  • File Upload with jsp & MultiPart

    Hi all,
    i've got a problem uploading a file from a multipart form.
    The file is correctly uploaded and i can open it, but I can't get the file name,
    In multipart.jsp fileName print out a null.
    Below the code. Can someone telle me where the error is?
    Thank's
    Kalvin
    this is the first page:
    prova.jsp:
    <form name="frmUp" action="multipart.jsp" method="POST" enctype="multipart/form-data">
    <input type="file" name="file"><br>
    <input type="submit">
    </form>
    multipart.jsp:
    <%
    String fileName = request.getParameter("nomeFile");
    String pathFile = "/myPath/";
    InputStream is = request.getInputStream();
    out.println("File name:"+fileName+"<br>");
    UploadFile uf = new UploadFile(pathFile, fileName);
    if (uf.upload(is))
         out.println("OK<br>");
    else
         out.println("NO OK <br>");
    %>

    you have to get the filename from UploadFile object probably. You definitely can't get it from request cuz multipart forms are handled specially. If it saves the file properly, then it's probably assuming a null filename means to use the name as it was uploaded, but UploadFile should be able to give you a File object for where the file was put.

  • URGENT.........File Upload using Servlets and jsp

    I am a new servlet programmer.......
    iam using tomcat server......
    can any one pls help in writing code for file upload using servlets and jsp without using multipart class or any other class like that....
    Please URGENT..

    Slow down! "Urgent" is from your perspective alone. I, myself, am not troubled or worried in the least.
    hi ugniss
    thanks for ur reply....sorry i was not
    y i was not asked not to use multipart class or any
    other class like that...is there any other
    possibility to do file uploading from jsp to
    servlet...
    Just as an aside, a JSP is a Servlet. But even if I move beyond that, the question does not make sense. If you want a "JSP to upload to a Servlet", then simply do so in memory. You are still (likely) within the same scope of a given request. However, if instead you are referring to a JSP that is displayed on a browser, then really you are talking about HTML, which is what the browser will receive. And since you are now talking about a browser, your only real, viable option is a multi-part file upload. So, it is either server or it is browser. And either way, the question leads to very established options, as outlined above.
    the main concept is.. in the browser the user selects
    a particular file and clicks the button upload..after
    clicking upload the jsp should sent the file to the
    servlet in streams...there the servlet gets in and
    saves in a server location........this is wat i hav
    to do...
    Okay. So, after reading my previous (redundant) paragraph, we have arrived at the crux of the issue. You have a JSP that will be output as HTML to a client (browser) which you want to upload content to your server (handled by a Servlet). So, you are now stuck again with multi-part. The requirement to not use multi-part is non-sensical. You can overcome it, say, if you write your own applet or standalone Swing client. However, if your users are invoking this functionality from a browser, you are limited by the options that W3C has provided you. Use multi-part.
    is there aby possibilty to do this.....can any one
    pls help....Take the advice to download and review Jakarta Commons FileUpload. Inform your management that their requirement makes no technical sense. Research on your own. There are dozens of examples (and tutorials) on file upload using multi-part. Embrace it. Live it. Love it.
    - Saish

  • File upload api

    Hi!
    I am looking for an api that handles file upload though jsp/servlet. I'm currently using the JspSmart smartUpload component but they looks like they have stop develop it so I'm am looking for an alternative.
    Thanks in advance
    Roland Carlsson

    Hi
    O'reilly is deloping som classe for file uploading.
    http://www.servlets.com/cos/index.html
    Cyrill

  • Uploading a file in a jsp page

    Hii Javaites
    I am developing an application in which i need to upload file from a jsp page, right now i am using tomcat can anyone tell me the code for uploading a file.
    Thanking in Advance

    Hi,
    For uploading file from jsp:
    1) Goto javazoom.com, then download latest version for upload the files.
    2) Extract the zip & thay giving four jar files
    they are:
    i)uploadbean.jar
    ii)struts.jar
    iii)fileupload.jar
    iv)cos.jar
    put all this jar in lib of u r web application
    ex:
    C:\jakarta-tomcat-5.0.25\webapps\URWEBAPP\WEB-INF\lib\
    3) Set it in class path
    4) create one jsp with file option<input type='file' name = 'somename'>
    5) In action page(next page)
    <%@ page language="java" import="javazoom.upload.*,java.util.*" %>
    <%@ page errorPage="error.jsp" %>
    <jsp:useBean id="upBean" scope="page" class="javazoom.upload.UploadBean" >
    <jsp:setProperty name="upBean" property="folderstore" value="c:/uploads" />
    </jsp:useBean>
    Set the folder where u want upload the particular file.
    MultipartFormDataRequest mrequest = new MultipartFormDataRequest(request);
    Hashtable files = mrequest.getFiles();
         UploadFile file = (UploadFile) files.get("somename");//Give name u r given in the previous page.
         String fileName = file.getFileName();     
    upBean.store(mrequest, "userFile");
    follow this steps it works fine.
    regards
    DRA

  • JSP : latest  JSTL, File Upload from web form Client to Server Question!

    I understand that within a JSP, It is possible to read a file from the Client by opening a Stream somehow.
    How do I code, within jsp/servlet (non tag) java code inside <% %>
    blocks, WITHOUT openening a new connection to the URL, an InputStream from a client web browser form, from a file upload coded using
    <input type="file" name="file1"/> ?
    I have previously achieved this quite simply with a FileInputStream
    with the previous version of JSTL.
    How may I do this with the latest version of JSTL, with this index.jsp?
    -with a simple text file.
    -with a Binary file (with DataInputStream)?
    <%--
    Document : index
    Created on : 27/01/2009, 3:08:32 PM
    Author : Zachary Mitchell
    --%>
    <%@page contentType="text/html" pageEncoding="UTF-8"%>
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
    "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>JSP Page</title>
    </head>
    <body>
    <h1 align="center">Hello World!</h1>
    <form name="form1" method ="POST" >
    <table align="center">
    <tr>
    <td>
    <input name="file1" type="file" align="center"></input>
    </td>
    </tr>
    <tr>
    <td>
    <input type="submit" value="submit" action="index.jsp" ></input>
    </td>
    </tr>
    </table>
    </form>
    <!--*********************************************************************** -->
    <%@ taglib uri="http://java.sun.com/jstl/core_rt" prefix="c" %>
    <%@page import = "java.io.*" %>
    <c:if test="${pageContext.request.method=='POST'}">
    <%
    File fileName = new File(request.getParameter("file1"));
    out.println(fileName.toString());
    FileInputStream stream = new FileInputStream(fileName);
    out.println(stream.toString());
    %>
    </c:if>
    <!--*********************************************************************** -->
    </body>
    </html>

    If I have:
    <!-- ***********************************************************************************-->
    <form name="form1" method="POST" enctype="multipart/form-data">
    <input name="file1" type="file"/>
    <input name="submit1" type="submit" value="Submit" action="index.jsp"/>
    </form>
    <!-- ***********************************************************************************-->
    and run this in an index.jsp, use browse to select my text file, and click SUBMIT.
    I can use:
    InputStreamReader reader = new InputStreamReader(new DataInputStream(request.getInputStream()))
    BufferedReader bufferedReader = new BufferedReader(reader);
    bufferedReader.readLine();...
    However, these is some HTML/POST related content around what multiple readLine();
    calls return.
    Is there an easy way, like using "${param.file1}",
    aside from [http://commons.apache.org/fileupload/|http://commons.apache.org/fileupload/],
    maybe using servlet style code, to get the File contents from a remote Client,
    to the remote Server servlet engine, AVOIDING ANY SUPERFLUOUS CONTENT,
    using version 1.12 of the JSTL, JSP 2.0,Tomcat 6?
    Just politely, yes, no, and how?
    Edited by: Zac1234 on Jan 29, 2009 3:27 AM
    Edited by: Zac1234 on Feb 1, 2009 8:29 PM

  • How to get full path of a file uploaded using file control on a jsp ?

    Hi all...
    I have a jsp on which i am using a file element (input type="file") to upload files present on the physical file system.. Thats working fine.. But i want to retrieve the full path of the file uploaded for further computation.
    What are the possible ways which can give me the full path ?? (e.g. "D:\data\text\Output.txt" )
    Thanks all for attending the question..
    Regards
    Prasad

    Some browsers send the full path. Some do not.
    You can not affect this in any way shape or form.
    All you can count on receiving is a filename - no path information.
    So you will have to have some other way for the user to pass along this information.
    If they are uploading to a "remote web site" they could specify a folder to put the uploaded file in.
    You could classify it and put all image files in "images" and all script files in "scripts" etc etc by default, and let the user deal with it in their own HTML.
    Hope this helps,
    evnafets

  • File upload, download using ADF UIX and not JSP

    I have examples for the file upload, download using JSP
    But I want to use ADF UIX. Look and feel in this is impressing and I want to use this. Any one have example for this.
    Users will select a file from their desktop
    This will be stored into the database (Any document. Word, Excel)
    When they query the records then the UIX column need to give a hyperlink. Clicking on the link should prompt to download the file to the local system

    Sure, I use the Apache Commons File Upload package, so that is what I will discuss here ( [Commons File Upload|http://commons.apache.org/fileupload/] ).
    The Commons File Upload uses instances of ProgressListener to receive upload progress status. So first create a simple class that implements ProgressListener:
    public class ProgressListenerImpl implements ProgressListener {
        private int percent = 0;
        public int getPercentComplete() {
            return percent;
        public void update(long pBytesRead, long pContentLength, int pItems) {
            if (pContentLength > -1) { //content length is known;
                percent = (new Long((pBytesRead / pContentLength) * 100)).intValue();
    }So in your Servlet that handles file upload you will need to create an instance of this ProgressListenerImpl, register it as a listener and store it in the session:
    ServletFileUpload upload = new ServletFileUpload();
    ProgressListenerImpl listener = new ProgressListenerImpl();
    upload.setProgressListener(listener);
    request.getSession().setAttribute("ProgressListener", listener);
    ...Now create another servlet that will retrieve the ProgressListenerImpl, get the percent complete and write it back (how you actually write it back is up to you, could be text, an XML file, a JSON object, up to you):
    ProgressListenerImpl listener = (ProgressListenerImpl) request.getSession().getAttribute("ProgressListener");
    response.getWriter().println("" + listener.getPercentComplete());
    ...Then your XMLHttpRequest object will call this second servlet and read the string returned as the percent complete.
    HTH

  • File upload and download using jsp/servlets

    How to upload any file to the server using jsp/servlets. . Help me out

    You can also try the Jenkov HTTP Multipart File Upload. It's a servlet filter that is easy to add to your web-project. After adding it, you can access both request parameters and the uploaded files easily. It's more transparent than Apache Commons File Upload. There is sufficient documentation to get you started, and there is a forum if you have any questions.
    Jenkov HTTP Multipart File Upload is available under the Apache license, meaning its free to use.

  • Difficulties in creating a JSP for File upload

    hello out there,
    im trying to create a ProcessUpload.jsp File which should handle a file upload from a channel in the portal. regarding a previously posted thread acording to fileupload i deployed this jsp-file in the regular webServerHierarchy so that you dont have to go into the desktopServlet Portal, which cant handle fileUpload.
    its location is this ../portal/test/ProcessUpload.jsp and it uses CustomTags referecens from /portal/WEB-INF/test.tld. i customized the deployment descriptor in /portal/WEB-INF/web.xml as well. but as soon as i try to put a taglib which uses this custom tags the server responses with an error.
    does anybody know how to deploy a global jsp file to handle file uploads, or something in particular how to deploy jsp with custom tags outside the desktopservlet but inside the portal webapp??
    i would be really thankful ;-)
    best regards
    martin

    hi alex,
    i allready tried to realize a channel with file upload download. channels are made up of jsp pages and when i am forwarding my form with enctype="multipart/form-data" encoding the desktop-servlet intercpets my entity-body.
    so what kind of channel you have thought about ??
    thanks for reply ;-)

  • File Upload JSP Portlet

    Hi,
    I want to upload files in a JSP portlet. I have java servlet and I can upload files successfully out of portal.
    How can I use these servlet in a JSP portlet to upload file?
    Thanks
    Ali Erkan

    http://jakarta.apache.org/commons/fileupload/
    http://jakarta.apache.org/commons/fileupload/using.html

  • Uploading of different file types in jsp

    hello,
    i have implemented a jsp web application where you can upload either
    a PDF file (file.pdf) or a latex file (file.tex).
    currently i have two different upload file tags so if a user wants to
    upload a pdf he/she will use the upload pdf path as shown in the
    code below:
    <!-- upload for latex file -->
    <form action="upload.jsp" name="upform"enctype="multipart/form-data">
    <input type="file" name="filename" size="50"><br>
    <input type="hidden" name="todo" value="upload">
    <input type="submit" name="Submit" value="Upload">
    </form>
    <h3>
    Upload for PDF Files Only </h3>
    <form action="uploadPDF.jsp" name="upform"enctype="multipart/form-data">
    <input type="file" name="PDFfilename" size="50"><br>
    <input type="hidden" name="todo" value="upload">
    <input type="submit" name="Submit" value="Upload">
    </form>
    As you can see above that there are two different paths.
    Does anyone know if a user submits a PDF the system should recognize the pdf file extension and call the uploadPDF.jsp page and
    if the file is a latex file then it should call the latex method.
    pls ur help will be appreciated,
    thanks,
    moh

    Hi there,
    Take a look at : http://jakarta.apache.org/commons/fileupload/
    You will need to download 2 additional JAR files to implement the file upload functionality
    1) commons-fileupload-1.1.1.jar - get it from http://jakarta.apache.org/site/downloads/downloads_commons-fileupload.cgi
    2) commons-io-1.3.jar - get it from
    http://jakarta.apache.org/commons/fileupload/dependencies.html
    As Gimball mentioned earlier first perform the test for the file type with Javascript - you can research on Google for the Javascript solution.
    After it passes the Javascript test here's some code with JSP, Servlets that might help you write your own solution:
    ~~~~~~~~~~~~~~~~~~~~~~~~~~
    somefile.jsp , located under for example:
    \p\test29\somefile.jsp
    ~~~~~~~~~~~~~~~~~~~~~~~~~~
    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
    <html>
      <head><title></title></head>
      <body>
      <form action="/fileUploadServlet" method="post" enctype="multipart/form-data">
          <input type="file" name="inputFile"/>
          <br/><br/>
          <input type="submit" name="submit" value="submit"/>
      </form>
      </body>
    </html>~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    FileUploadServlet
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    package test29;
    import org.apache.commons.fileupload.servlet.ServletFileUpload;
    import org.apache.commons.fileupload.servlet.ServletRequestContext;
    import org.apache.commons.fileupload.RequestContext;
    import org.apache.commons.fileupload.FileItemFactory;
    import org.apache.commons.fileupload.FileItem;
    import org.apache.commons.fileupload.FileUploadException;
    import org.apache.commons.fileupload.disk.DiskFileItemFactory;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import javax.servlet.ServletException;
    import javax.servlet.RequestDispatcher;
    import java.io.IOException;
    import java.util.List;
    import java.util.Iterator;
    public class FileUploadServlet extends HttpServlet {
        public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            doPost(request, response);
        public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            RequestContext requestContext = new ServletRequestContext(request);
            boolean isMultipart = ServletFileUpload.isMultipartContent(requestContext);
            System.out.println(" isMultipart : " + isMultipart);
            // Create a factory for disk-based file items
            FileItemFactory factory = new DiskFileItemFactory();
            // Create a new file upload handler
            ServletFileUpload upload = new ServletFileUpload(factory);
            // Parse the request
            List<FileItem> items = null;
            try {
                items = upload.parseRequest(request);
                Iterator fileItemsIter = items.iterator();
                while (fileItemsIter.hasNext()) {
                    FileItem item = (FileItem) fileItemsIter.next();
                    if (item.isFormField() == false) {
                        String contentType = processUploadedFile(item);
                        if (contentType.equalsIgnoreCase("application/pdf")) {
                            request.setAttribute("contentType", "application/pdf");
                        } else if (contentType.equalsIgnoreCase("application/tex")) {
                            request.setAttribute("contentType", "application/tex");
                        } else {
                            request.setAttribute("contentType", "other");
                        RequestDispatcher requestDispatcher = getServletContext().getRequestDispatcher("/p/test29/fileReceive.jsp");
                        requestDispatcher.forward(request, response);
            } catch (FileUploadException e) {
                e.printStackTrace();
        private String processUploadedFile(FileItem item) {
            String contentType = "unknown";
            if (!item.isFormField()) {
                String fieldName = item.getFieldName();
                String fileName = item.getName();
                contentType = item.getContentType();
                boolean isInMemory = item.isInMemory();
                long sizeInBytes = item.getSize();
                /* Print test output on console */
                System.out.println(" Field Name : " + fieldName);
                System.out.println(" File Name : " + fileName);
                System.out.println(" Content Type : " + contentType);
                System.out.println(" Is in Memory : " + isInMemory);
                System.out.println(" Size in Bytes : " + sizeInBytes);
                if (contentType.equalsIgnoreCase("application/pdf")) {
                    System.out.println("This is a PDF document.");
            }//if (!item.isFormField())
            return contentType;
        }//private String processUploadedFile(FileItem item)
    }~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    Add these to your /WEB-INF/web.xml
    First you define the servlet, and provide a URL pattern.
    The URL pattern is the form's action in the above JSP file.
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        <servlet>
            <servlet-name>FileUploadServlet</servlet-name>
            <servlet-class>test29.FileUploadServlet</servlet-class>
        </servlet>
        <servlet-mapping>
            <servlet-name>FileUploadServlet</servlet-name>
            <url-pattern>/fileUploadServlet</url-pattern>
        </servlet-mapping>~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    fileReceive.jsp
    located under:
    \p\test29\fileReceive.jsp
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <html>
      <head><title>Process File</title></head>
      <body>
      Uploaded File Content Type is : <%=request.getAttribute("contentType")%>
      </body>
    </html>In the above JSP you can test for the contentType, if it is not PDF or TEX then perform the next action.
    The above code is not very clean or the best way to accomplish this, but it should at least help you get started and it works.

Maybe you are looking for

  • (6230i) Unable to delete...file from phone memory

    Hello ...please help ... ...im having trouble deleting file from my phone memory (music file) that i downloaded from www.uaemobiles.com/wap/down.aspx?MN=3332383573&CD=​74752 file is stil in my service inbox.. please guide me ...i wanna get rid of tha

  • Please fix the lack of critical functionalities in Numbers

    The new iWork came with a host of new features. However two issues will keep me from switching from MS Office to iWork completely. Both these issues are with Numbers and extend to use of Charts in other iWork applications. Issue 1: It's quite unbelie

  • Check printing and basic time keeping

    I am looking for software to print checks and do basic time keeping. Any recommendations other than Quickbooks?

  • Where can I find a g5 iMac startup disk?

    Recently, I decided to sell my old iMac G5, as I don't need it anymore, as i have a new mac... I realized that I needed to wipe the memory before I could sell it, so I inserted the installation CD into the Mac, and went through the stages, selecting

  • IPhoto crashes when loading

    iPhoto crashes when loading.  I am on 9.1.2 & I think this may have started after the update was applied on the 27/4 and the error message does not mean much to me Process:         iPhoto [1472] Path:            /Applications/iPhoto.app/Contents/MacO