Saturday, May 19, 2018

Uploading file name or image to Database

Leave a Comment

Uploading file name or image to Database 

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

Here is the Code of the file Uploading using Servlets in JAVA and saving the image and filename of image in the database.

Name the HTML page as file.html

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

Write the servlet code and specify the name of the servlet as

package com.struts;

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

public class UploadFile extends HttpServlet {

 public void doPost(HttpServletRequest req, HttpServletResponse res) {

   try {

    Connection conn = DriverManager.getConnection("jdbc: mysql: //localhost/test?user=root&password=test");
      PrintWriter out = res.getWriter();

      //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("\"");
           String extension_saveName = saveFile.substring(extension_save);

           //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);

              int file_No = 22; String pathname_dir = "D: \\rk\\" + saveFile; File filepath = new File(pathname_dir); out.println("filepath_“ + filepath); fileOut = new FileOutputStream(filepath); fileOut.write(dataBytes, startPos, (endPos - startPos)); fileOut.flush(); out.println(" < h1 > your files are saved < /h1></body > < /html>");

               File database_filename = new File(pathname_dir); fis = new FileInputStream(database_filename); PreparedStatement ps = conn.prepareStatement("insert into test(fname) values( ? )"); ps.setString(1, database_filename.getName()); ps.executeUpdate(); ps.close(); flag = 1;


              if (flag == 1) {
             } catch (Exception e) {
              System.out.println("Exception Due to" + e);

The above code is used to save the path in the Database where(in Which directory/folder) the file is saved .
If you want to save the image into data base the just modify the part of the above code like the below specified.
Here note that the image column data type should be take as blob.

File database_filename = new File(pathname_dir);
fis = new FileInputStream(database_filename);
PreparedStatement ps = conn.prepareStatement("insert into test(fname, image) values( ? , ? )");
ps.setString(1, database_filename.getName());
ps.setBinaryStream(2, fis, database_filename.length())

//ps.setBinaryStream(int parameterIndex,InputStream x,int length)

To know more about BinaryStream and the methods of sql package.

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.


If You Enjoyed This, Take 5 Seconds To Share It


Post a Comment