0

I'm using below code to upload the file to server. Is it proper? The path "d:/new" in the code, is it server path or client PC path. Do i have to specify client pc path anywhere. Or it will directly take the path while clicking browse button and select the file? Is there any better approach other than this to upload file to server?

index.html

    <html>  
    <body>  
<form class="form-group" action="go" method="post" enctype="multipart/form-data">
                                            <%

                                                Connection connection = null;
                                                Statement statement = null;
                                                String error = "";

                                                try {
                                                    Class.forName("com.mysql.jdbc.Driver").newInstance();
                                                    connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/lms_data", "root", "");
                                                    statement = connection.createStatement();
                                                    ResultSet resultset = statement.executeQuery("select * from assessment_type");
                                                    connection.setAutoCommit(false);
                                            %>


                                            <label>Assessment Type</label>
                                            <select class="form-control" name="assessment_type_id">
                                                <%  while (resultset.next()) {%>
                                                <option value="<%= resultset.getString(1)%>"><%= resultset.getString(2)%></option>

                                                <% } %>
                                            </select>

                                            <%
                                            ResultSet resultset_cat_id = statement.executeQuery("select * from course_category");
                                            %>
                                            <br/><label>Category Name</label>
                                            <select class="form-control" name="category_id">
                                                <%  while (resultset_cat_id.next()) {%>
                                                <option value="<%= resultset_cat_id.getString(1)%>"><%= resultset_cat_id.getString(2)%></option>

                                                <% } %>
                                            </select>
                                            <%
                                                } catch (Exception e) {
                                                    if (!connection.isClosed()) {
                                                        connection.close();
                                                    }
                                                    out.println(e);
                                                    e.printStackTrace();
                                                }
                                            %>
                                            <label class="control-label">Select File</label>
                                            <input type="file" name="file" id="file"><br/>


                                            <input type="submit" name="submitform" class="btn btn-primary" value="Submit" style="width:20%;border-radius:0px;"><br/><br/>



                                        </form> 
    </body>  
    </html> 

UploadServlet.java

import java.io.*;  
import javax.servlet.ServletException;  
import javax.servlet.http.*;  
import com.oreilly.servlet.MultipartRequest;  

public class UploadServlet extends HttpServlet {  

public void doPost(HttpServletRequest request, HttpServletResponse response)  
    throws ServletException, IOException {  

response.setContentType("text/html");  
PrintWriter out = response.getWriter();  

MultipartRequest m=new MultipartRequest(request,"d:/new");  
out.print("successfully uploaded");  
}  
} 

web.xml

<web-app>  

<servlet>  
<servlet-name>UploadServlet</servlet-name>  
<servlet-class>UploadServlet</servlet-class>  
</servlet>  

<servlet-mapping>  
<servlet-name>UploadServlet</servlet-name>  
<url-pattern>/go</url-pattern>  
</servlet-mapping>  

</web-app> 
ViRaPa
  • 13
  • 1
  • 9
  • Please watch out next time how you paste your code here. It should be easy to read (not multiple files in one code block) and you should have formatted it correctly. I did a fast improvement because you are new :) (I can't format the code atm so that have someone else to do). – CodeShark Aug 28 '17 at 11:43

1 Answers1

0

Since you are using multipart/formdata, Try this piece of code to grap the file and write it to your Project in your defined folder.
Create a folder (i.e : document/excel/) inside your project.

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    String fileName = "";

    if (!ServletFileUpload.isMultipartContent((HttpServletRequest) request)) {
        PrintWriter writer = response.getWriter();
        writer.println("Error: Form must has enctype=multipart/form-data.");
        writer.flush();
        return;
    }
    DiskFileItemFactory factory = new DiskFileItemFactory();
    factory.setSizeThreshold(3145728);
    factory.setRepository(new File(System.getProperty("java.io.tmpdir")));
    ServletFileUpload upload = new ServletFileUpload((FileItemFactory) factory);
    upload.setFileSizeMax(41943040);
    upload.setSizeMax(52428800);
    String uploadPath = String.valueOf(this.getServletContext().getRealPath("")) + File.separator + "foldername"; // example : (documents/excel/)
    File uploadDir = new File(uploadPath);
    if (!uploadDir.exists()) {
        uploadDir.mkdir();
    }
    try {

        List<FileItem> formItems = upload.parseRequest(request);
        if (formItems != null && formItems.size() > 0) {
            for (FileItem item : formItems) {
           if (item.isFormField())
                  {

                    if ("assessment_type_id".equals(item.getFieldName()))
                    assessment= item.getString();
                    else if ("category_id".equals(item.getFieldName()))
                    categoryid= Integer.parseInt(item.getString());


                  }
                 else {
                    fileName = new File(item.getName()).getName();
                    String ext1 = FilenameUtils.getExtension(fileName);
                    fileName = fileName+ "." + ext1;
                    String filePath = String.valueOf(uploadPath) + File.separator + fileName;
                    File storeFile = new File(filePath);
                    item.write(storeFile);
                    request.setAttribute("message", "File Uploaded Successfully");

                }
// then Here update the Database

            }

        }
    } catch (Exception ex) {
        request.setAttribute("message", (Object) ("There was an error: " + ex.getMessage()));

    }
}

Uploadpath var will take you to your project location then you check if there is some form item posted, lastly write the file into that location.
Hope this works !

  • Is it possible to use this code in jsp file instead of java class?how? – ViRaPa Aug 29 '17 at 04:52
  • yes, but its better to create a Servlet class and it has two predefined methods in it, 1- doGet() 2- doPost() use my code in post method and set the html Form action to "Post" – Ahmer Qureshi Aug 29 '17 at 05:45
  • code works fine. But in form i have some code to be executed after the file is uploaded. How to do it. How to come back to the jsp in which form is there, and how to execute that code only after the file is uploaded? – ViRaPa Aug 29 '17 at 06:16
  • Basically i want to return file name to the previous jsp which contains form and do some database inserts. And i want that piece of code to be excecuted only after file upload – ViRaPa Aug 29 '17 at 06:19
  • ok i got it : **use this :** `response.sendRedirect("pagename.jsp?filename=something.jpg");` at the end of doPost method(); – Ahmer Qureshi Aug 29 '17 at 06:31
  • but how to execute rest of the jsp code in previous jsp page. I mean the one in which form is there. – ViRaPa Aug 29 '17 at 07:01
  • Copy the rest of code i suppose you want to add that into Database. So copy that code and write it after you do `item.write(storeFile);` in Servlet and do whatever you have to do like Database manipulation and finally `response.sendRedirect` back to jsp page. – Ahmer Qureshi Aug 29 '17 at 07:08
  • can i include some other input fields in the form? I want to give some drop down input fields. The drop down content will be from database. At this time the filename at this line fileName = new File(item.getName()).getName(); coming empty. I have edited the question with new form. – ViRaPa Aug 29 '17 at 07:39
  • @ViRaPa yes you can. i have edited my code, in which first if condition will check is there is any Form Fields and you store those values in variables, in Else you store your file in some path and then update the Database. for filename you can manually give the filename by using random string. – Ahmer Qureshi Aug 29 '17 at 07:56
  • can i upload all files inside a folder to server? file names are unknown, but folder name is known. Whatever files are there inside it needs to be uploaded to server. – ViRaPa Aug 30 '17 at 05:08
  • Is there any way to delete the same uploaded file at the end? – ViRaPa Sep 01 '17 at 04:42