Sir ,I am trying to upload a file but
Hi,
If you wish to upload files in the local context of your project, then you may first create a folder under WEB_INF. call it anything you want. Then considering the fact that you are a beginner, I would suggest that you create a servlet and call it from the page using method POST. Within the servlet, there would be two options for you to explore:- 1. saving the file uploaded into the database, which would require the use of either JDBC or JPA, whichever is known to you. 2. saving the file in a folder.
code is given below:-
package pack; import java.io.*; import java.sql.DriverManager; import java.util.Scanner; import javax.servlet.*; import javax.servlet.annotation.WebServlet; import javax.servlet.http.*; import javax.servlet.annotation.MultipartConfig; import java.sql.*; /** * Servlet implementation class uploadServlet */ @WebServlet("/upload.do") @MultipartConfig public class uploadServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub Part p1=request.getPart("title"); Part p2=request.getPart("filesel"); InputStream is=p2.getInputStream(); Scanner sc=new Scanner(p1.getInputStream()); String title=sc.next(); sc=new Scanner(p2.getContentType()); String type=sc.next(); try { String path=request.getServletContext().getRealPath("folder url where u want to store your uploaded file"); FileOutputStream fos=new FileOutputStream(path); byte buf[]=new byte[is.available()]; is.read(buf); fos.write(buf); fos.flush(); fos.close(); // use this part only if you wish to store files in database Class.forName("sun.jdbc.odbc.Driver"); Connection con=DriverManager.getConnection("jdbc:odbc:databasename"); PreparedStatement ps=con.prepareStatement("insert in table (picName,picPath) values(?,?) "); ps.setString(1, title); ps.setString(2, path); ps.execute(); ps.close(); con.close(); } catch(Exception e) { e.printStackTrace(); } } }
Note that the part where I set the path for storage has to be either one of local context as mentioned before or it can be a folder created anywhere in your machine.
Hope this solves your query.
Regards, Abhineet Verma
Ads