Saturday, May 19, 2018

File Uploading Using Servlet with Source Code

Leave a Comment

File Uploading Using Servlet with Source Code



This is an example of the file Uploading in Java using Servlets . This file uploading concept Works with the Java as follows.




The Servlet api consists of the method called getContentType which takes the file request as the input and generates the file to the specified path

Here is the Code of the file Uploading using Servlets in JAVA.

Name the HTML page as file.html



<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<form method="post" action="servlet/UploadFile" enctype="multipart/form-data">
Name
<input type="text" name="uname"/>
File
<input type="file" name="upfile"/>
<input type="submit"/>


Specify the action path to which servlet to must follow and the type of the data to send to the servlet is specified by the enctype=”multipart/form-data”

Once the request goes to the servlet the request is collected through getContentType() method (to learn more  about getContentType)

Write the servlet code and specify the name of the servlet as UploadFile.java


package com.myapp.struts;

import java.io.*;
import java.sql.*;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletInputStream.*;
import java.io.PrintWriter;

public class UploadFile extends HttpServlet {

 public void doPost(HttpServletRequest req, HttpServletResponse res) {

   try {

    //out.println(”<br>Content type is :: ” +contentType);
    //to get the content type information from JSP Request Header

    String contentType = req.getContentType();
    int flag = 0;
    FileInputStream fis = null;
    FileOutputStream fileOut = null;

    //here we are checking the content type is not equal to Null and as well as the passed data from mulitpart/form-data is greater than or equal to 0

    if ((contentType != null) && (contentType.indexOf(multipart / form - data) >= 0)) {
     DataInputStream in = new DataInputStream(req.getInputStream());

     //we are taking the length of Content type data

     int formDataLength = req.getContentLength();
     byte dataBytes[] = new byte[formDataLength];
     int byteRead = 0;
     int totalBytesRead = 0;

     //this loop converting the uploaded file into byte code

     while (totalBytesRead < formDataLength) {
      byteRead = in .read(dataBytes, totalBytesRead, formDataLength);
      totalBytesRead += byteRead;
     }

     String file = new String(dataBytes);

     //for saving the file name

     String saveFile = file.substring(file.indexOf(filename = \”") + 10);
        saveFile = saveFile.substring(0, saveFile.indexOf(”\n”)); out.println(”savefiledddd“ + saveFile); int extension_save = saveFile.lastIndexOf(”\”");

         //Here we are invoking the absolute path out of the encrypted data

         saveFile = saveFile.substring(saveFile.lastIndexOf(”\\”) + 1, saveFile.indexOf(”\”"));
           int lastIndex = contentType.lastIndexOf(” = ”); String boundary = contentType.substring(lastIndex + 1, contentType.length()); int pos;

           //extracting the index of file

           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;

            out.println(savefile + saveFile);

            String pathname_dir = D: \\test\\” + saveFile; File filepath = new File(pathname_dir); out.println(filepath_ + filepath); fileOut = new FileOutputStream(filepath); fileOut.write(dataBytes, startPos, (endPos - startPos)); fileOut.flush(); fileOut.close(); fis.close();

           }

          } catch (Exception e) {
           System.out.println(Exception Due to + e);
           e.printStackTrace();
          }
         }
        }

Here you are specifying the path that the file is to save in your local disk i.e
your file will be saving in the test folder with the name of the file as original name of the file you are invoking.

Here is Deployment descriptor to pass the request from the html to Servlet program. save these with the name web.xml in the WEB-INF directory.


<servlet>
<servlet-name>UploadFile</servlet-name>
<servlet-class>com.myapp.struts.UploadFile</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>UploadFile</servlet-name>
<url-pattern>/servlet/UploadFile</url-pattern>
</servlet-mapping>
If You Enjoyed This, Take 5 Seconds To Share It

0 comments:

Post a Comment