0

I am very new to servlet technology. I want to upload a file from the local file system (i.e., client machine) to the server, which is running on Tomcat. Can someone please tell me how to do this.

I am using html input element type file (<input type="file"...>) and form action attribute posts the data to a servlet.

plz help me.

4 Answers 4

3

Use the Apache Commons File Upload.

Apache.org seems to be having some issues right now, so here's the Google cached page.

1

This is not included in the servlet api, but is available through http://commons.apache.org/fileupload/

Basically this uses the IO streaming included in the servlet API to process uploaded stream data - I think there was plans to include file upload functionality out of the box in the newest version of the API, but this has always worked for me.

1

The best option would be to use some external library which can handle file upload. If you are using Spring, then check out this page: http://static.springsource.org/spring/docs/3.0.0.M3/spring-framework-reference/html/ch16s08.html.

Spring is internally using Apache Commons for file upload, so if you don't use Spring, or you would like just stick to Servlet API, I suggest using Commons as well: http://commons.apache.org/fileupload/

1

Pass the file from JSP or HTML using file Upload Component. and set servlet.java in form action.

Servlet.java

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;

public class UploadServlet extends HttpServlet{ 
     public void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException {
     response.setContentType("text/html");
     PrintWriter out = response.getWriter();

    String saveFile="";
    String contentType = request.getContentType();
    if((contentType != null)&&(contentType.indexOf("multipart/form-data") >= 0)){
    DataInputStream in = new DataInputStream(request.getInputStream());
    int formDataLength = request.getContentLength();
    byte dataBytes[] = new byte[formDataLength];
    int byteRead = 0;
    int totalBytesRead = 0;
    while(totalBytesRead < formDataLength){
    byteRead = in.read(dataBytes, totalBytesRead,formDataLength);
    totalBytesRead += byteRead;
   }
    String file = new String(dataBytes);
    saveFile = file.substring(file.indexOf("filename=\"") + 10);
    saveFile = saveFile.substring(0, saveFile.indexOf("\n"));
    saveFile = saveFile.substring(saveFile.lastIndexOf("\\") + 1,saveFile.indexOf("\""));
    int lastIndex = contentType.lastIndexOf("=");
    String boundary = contentType.substring(lastIndex + 1,contentType.length());
    int pos;
    pos = file.indexOf("filename=\"");
    pos = file.indexOf("\n", pos) + 1;
    pos = file.indexOf("\n", pos) + 1;
    pos = file.indexOf("\n", pos) + 1;
    int boundaryLocation = file.indexOf(boundary, pos) - 4;
    int startPos = ((file.substring(0, pos)).getBytes()).length;
    int endPos = ((file.substring(0, boundaryLocation)).getBytes()).length;
    File ff = new File(saveFile);
    FileOutputStream fileOut = new FileOutputStream(ff);
    fileOut.write(dataBytes, startPos, (endPos - startPos));
    fileOut.flush();
    fileOut.close();
    out.println("You have successfully upload the file:"+saveFile);
    Connection connection = null;
    String connectionURL = "jdbc:mysql://localhost:3306/test";
    ResultSet rs = null;
    PreparedStatement psmnt = null;
    FileInputStream fis;
    try{
    Class.forName("com.mysql.jdbc.Driver").newInstance();
    connection = DriverManager.getConnection(connectionURL, "root", "root");
    File f = new File(saveFile);
    psmnt = connection.prepareStatement("insert into file(file_data) values(?)");
    fis = new FileInputStream(f);
    psmnt.setBinaryStream(1, (InputStream)fis, (int)(f.length()));
    int s = psmnt.executeUpdate();
    if(s>0){
    System.out.println("Uploaded successfully !");
    }
    else{
    System.out.println("Error!");
    }
    }
    catch(Exception e){
        e.printStackTrace();
        }
    }
  }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.