Saturday, May 9, 2015

How to upload a file at server and store path in database in java.

To upload a file at server and storing a path in database we have to use JavaJoom Api. Add "uploadbean.jar" in your application and follow below steps –






Step 1- Create a form by taking at least one of the file type field

1
<input type="file" id="fileField" name="fileField" multiple  />

Step 2- Add enctype="multipart/form-data" attribute in form tag

1
<form   name="frm" action="fileuploadaction.jsp" method="post" enctype="multipart/form-data">

Step 3- Create MultipartFormDataRequest object at server side by handling the client request

1
MultipartFormDataRequest nreq = new MultipartFormDataRequest(request);

Step 4- Create FileMover object to set the custom file name to file name which is coming from form.

1
2
uploadutilities.FileMover fileMover = new uploadutilities.FileMover();
fileMover.setNewfilename(idname);

Step 5- Create UploadBean object for uploading a file to a particular location.

1
2
3
4
javazoom.upload.UploadBean upBean = new javazoom.upload.UploadBean();
upBean.addUploadListener(fileMover);    upBean.setFolderstore("H:/Our_Projects/UI Related POC/UI RelatedPOC/AllPOC/web/JSP/images");
upBean.setOverwrite(false);
upBean.store(nreq, "fileField");

Step 6- Create connection to a database and insert the details in table.

Step 7- Get the details from database and display it into jsp.

Project Folder Structure-


Example : Create Table

1
CREATE TABLE usertest ( 'userid VARCHAR(50) NOT NULL, photpath VARCHAR(150) NOT NULL ) ;

fileupload.jsp


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Upload a file</title>
    </head>
    <body>
        <h1>Upload a file</h1>
        <form   name="frm" action="fileuploadaction.jsp" method="post" enctype="multipart/form-data">
            <fieldset style="width:600px">
                <legend>
                    <b>Upload Photo</b>
                </legend>
                <table style="width:500px">
                    <tr>
                        <td style="width:30%;">Enter id/name :</td>
                        <td>
                            <input type="text" id="idname" name="idname" />
                        </td>
                    </tr>
                    <tr>
                        <td>Upload Photo :</td>
                        <td>
                            <input type="file" id="fileField" name="fileField" multiple  />
                        </td>
                    </tr>
                    <tr>
                        <td colspan="2" style="align:center;">
                            <input type="submit" value="Upload"  />
                        </td>
                    </tr>
                </table>
            </fieldset>
        </form>
    </body>
</html>

fileuploadaction.jsp

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
<%@page import="java.sql.ResultSet"%>
<%@page import="java.sql.PreparedStatement"%>
<%@page import="java.sql.DriverManager"%>
<%@page import="java.sql.Connection"%>
<%@page import="java.io.File"%>
<%@page import="javazoom.upload.MultipartFormDataRequest"%>
<%
    MultipartFormDataRequest nreq = new MultipartFormDataRequest(request);
    String idname = nreq.getParameter("idname").trim();
    File deleteFile1 = new File("H:/Our_Projects/UI Related POC/UI Related POC/AllPOC/web/JSP/images/" + idname);
    // check if the file is present or not
    if (deleteFile1.exists()) {
        deleteFile1.delete();
    }
    uploadutilities.FileMover fileMover = new uploadutilities.FileMover();
    fileMover.setNewfilename(idname);
    javazoom.upload.UploadBean upBean = new javazoom.upload.UploadBean();
    upBean.addUploadListener(fileMover);
    upBean.setFolderstore("H:/Our_Projects/UI Related POC/UI Related POC/AllPOC/web/JSP/images");
    upBean.setOverwrite(false);
    upBean.store(nreq, "fileField");
    String userphotopath = "images/" + idname;
    Thread.sleep(2000L);
    Class.forName("com.mysql.jdbc.Driver");
    Connection connection=DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","root");
    PreparedStatement pinsert = connection.prepareStatement("insert into usertest values(?,?)");
    pinsert.setString(1, idname);
    pinsert.setString(2,userphotopath);
    pinsert.executeUpdate();
    pinsert = connection.prepareStatement("select * from usertest");
    ResultSet rs = pinsert.executeQuery();
%>

<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Uploaded file</title>
    </head>
    <body>
        <h1>Uploaded file</h1>
        <form   name="frm" action="fileuploadaction.jsp" method="post" enctype="multipart/form-data">
            <fieldset style="width:600px">
                <legend>
                    <b>User Details</b>
                </legend>
                <table style="width:500px">
                    <tr>
                        <td style="width:30%;">User id/name :</td>
                        <td><%=idname%></td>
                    </tr>
                    <tr>
                        <td>Uploaded Photo :</td>
                        <td><img src="<%=userphotopath%>" style="width:100px; height: 100px"/></td>
                    </tr>
                </table>
            </fieldset>
        </form>
        <fieldset style="width:600px">
            <legend>
                <b>All Users Details</b>
            </legend>
            <table>
                <%
                    while(rs.next()){
                %>
                <tr style="border: 1px solid gainsboro;">
                    <td><%=rs.getString("userid")%></td>
                    <td><img src="<%=rs.getString("photpath")%>" style="width:50px; height: 50px"/></td>
                </tr>
                <%
                    }
                %>
            </table>
        </fieldset>
    </body>
</html>

FileMover.java (under uploadutilities package)

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
package uploadutilities;

import java.io.File;
import java.io.FileOutputStream;
import java.io.Serializable;
import java.util.Vector;
import javazoom.upload.UploadFile;
import javazoom.upload.UploadListener;
import javazoom.upload.UploadParameters;

/**
 * This class implements a JavaBean, notified by UploadBean, that renames
 * the uploaded "filename" as "prefixfilenamepostfix". For instance, document.pdf
 * will become prefixdocument.pdfpostfix. It's also possible the rename the full
 * "filename" through setNewfilename() method.
 * This class only supports folderstore model.
 */
public class FileMover implements UploadListener, Serializable
{
  private String prefix = "";
  private String postfix = "";
  private String newfilename = null;
  private Vector filenames = null;
  private boolean copyfile = false;
  private String altfolder = null;
  private char[] inputchar = null;
  private char[] outputchar = null;

  public FileMover()
  {
    filenames = new Vector();
  }

  /**
   * Copy file and rename the copy if enabled. Rename file if disabled.
   * @param b
   */
  public void enableCopy(boolean b)
  {
    copyfile = b;
  }
  /**
   * Set filename prefix.
   * @param prefix
   */
  public void setPrefix(String prefix)
  {
    this.prefix = prefix;
  }

  /**
   * Return filename prefix.
   * @return
   */
  public String getPrefix()
  {
    return prefix;
  }

  /**
   * Set filename postfix.
   * @param postfix
   */
  public void setPostfix(String postfix)
  {
    this.postfix = postfix;
  }

  /**
   * Return filename postfix.
   * @return
   */
  public String getPostfix()
  {
    return postfix;
  }
  /**
   * Set new filename. The uploaded filename will be renamed by given filename.
   * @param newfilename
   */
  public void setNewfilename(String newfilename)
  {
    this.newfilename = newfilename;
  }
  /**
   * Return new filename.
   * @return
   */
  public String getNewfilename()
  {
    return this.newfilename;
  }
  /**
   * Set characters to replace in filename. For instance replace space (" ") by underscore ("_");
   * @param input array of char to be replaced 
   * @param output array of char replacing input
   */
  public void setReplaceChar(char[] input, char[] output)
  {
   this.inputchar = input;
   this.outputchar = output;
  }
  /**
   * Set alternate folder to copy/move the uploaded file.
   * @param postfix
   */
  public void setAltFolder(String folder)
  {
    this.altfolder = folder;
  }
  /**
   * Get alternate folder to copy/move the uploaded file.
   * @return
   */
  public String getAltFolder()
  {
    return altfolder;
  }
  /**
   * UploadListener callback.
   * @param params uploaded parameters.
   * @param file uploaded file.
   */
  public void fileUploaded(UploadParameters params, UploadFile file)
  {
    long filesize = file.getFileSize();
    String contentType = file.getContentType();
    String oldfilename = file.getFileName();
    String altfilename = oldfilename;
    String newfilename = oldfilename;
    if ((inputchar != null) && (outputchar != null) && (inputchar.length==outputchar.length))
    {
     for (int c=0;c<inputchar.length;c++)
     {
   oldfilename = oldfilename.replace(inputchar[c],outputchar[c]);
     }
    }
    if (this.newfilename != null) oldfilename = this.newfilename;
    String currentfolder = params.getStoreinfo();
    // File Location is saved in the upload bean params.getStoreInfo()
    if ((prefix != null) && (prefix.length() > 0))
    {
      oldfilename = prefix + oldfilename;
    }
    if ((postfix != null) && (postfix.length() > 0))
    {
      oldfilename = oldfilename + postfix;
    }
    newfilename = oldfilename;
    try
    {
      if (copyfile == true)
      {
        if (altfolder != null) currentfolder = altfolder;
        byte[] data = file.getData();
        FileOutputStream out = new FileOutputStream(currentfolder + File.separator + newfilename);
        out.write(data);
        out.close();
      }
      else
      {
        File fold = new File(currentfolder + File.separator + file.getFileName());
        if (altfolder != null) currentfolder = altfolder;
        File fnew = new File(currentfolder + File.separator + newfilename);
        fold.renameTo(fnew);
      }
      UploadParameters newparams = new UploadParameters(newfilename, filesize, contentType, params.getStoremodel(),currentfolder,altfilename);

      filenames.add(newparams);
    }
    catch (Exception e)
    {
      System.err.println(e.toString());
    }
    // Remove uploaded file from memory.
    file.reset();
  }
  /**
   * Return renamed filename.
   * @return
   */
  public String getFileName()
  {
    if (filenames.size() > 0)
    {
        UploadParameters up =  (UploadParameters) filenames.elementAt(filenames.size()-1);
        return up.getFilename();
    }
    else return null;
  }
  /**
   * Return renamed filenames (for multiple uploads) as UploadParameters.
   * @return Vector of UploadParameters.
   */
  public Vector getFileNames()
  {
    return filenames;
  }
  public void fileUploadStarted(File file, int contentlength, String contenttype)
  {
  }
  public void dataRead(int read)
  {
  }
}

No comments :

Post a Comment