Latest Tutorials| Questions and Answers|Ask Questions?|Site Map



Home Answers Viewqa JSP-Servlet code error.please help.urgent!!!!!
Login         

View Questions and Answers by Category

Advertisements


 
Have Programming Question? Ask it here!
 
 
 


madem sravani
code error.please help.urgent!!!!!
1 Answer(s)      2 years and 10 months ago
Posted in : JSP-Servlet


I am uploading a file.but i get an error.please correct the code. i get an error where check2 is not being printed.plz correct

package sercls; import java.lang.Class; import java.lang.String; import java.lang.Exception;

import java.io.PrintWriter; import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader;

import java.sql.Types; import java.sql.ResultSet; import java.sql.Statement; import java.sql.Connection; import java.sql.DriverManager;

import java.util.List; import java.util.Iterator;

import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpSession; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.DiskFileUpload; import org.apache.commons.fileupload.FileUploadException;

public class saveserv extends HttpServlet {

@Override protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { Connection connection = null; Statement statement = null;

    String driver = null;
    String url    = null;
    String userid = null;
    String pass   = null;

    String query  = null;

    String  error_message = null;
    boolean error_occured = false;

    boolean tableCreated = false;

    DiskFileUpload upload   = null;
    BufferedReader queries  = null;
           List items = null;

    HttpSession session   = req.getSession(false);

        driver  = session.getAttribute("driver").toString();
        url     = session.getAttribute("url").toString();
        userid  = session.getAttribute("userid").toString();
        pass    = session.getAttribute("pass").toString();

        PrintWriter out=res.getWriter();

        out.println("sdfsfd");

            out.println(driver+url);
        try {
         out.println("check");
                        upload = new DiskFileUpload();
                        out.println("check1"+upload+"***************"+items);
            items  = upload.parseRequest(req);
                    out.println("check2");
            Iterator iter = items.iterator();
                            out.println("items--------"+items);
            while (iter.hasNext()) {
                FileItem item = (FileItem) iter.next();
                if(!item.isFormField()) {
                    queries = new BufferedReader(new InputStreamReader(item.getInputStream()));
                                            out.println("queries----------"+queries);
                }
            }
        }
        catch(Exception e)  {
            error_occured = true;
            error_message = e.toString();

        }
             /*if(!error_occured)   {
            try {
                Class.forName(driver);
                connection  = DriverManager.getConnection(url,userid,pass);
                statement   = connection.createStatement();
            }
            catch(Exception e) {
                error_occured = true;
                error_message = e.toString();
            }
        }
         if(error_occured)
             res.sendRedirect("error occured");
        else {
            try {
                while(true) {
                    query = queries.readLine();
                    if(query == null)   break;
                    else {
                        statement.execute(query);
                        if(query.toUpperCase().startsWith("CREATE")) tableCreated = true;
                    }
                }
            }
            catch(Exception e) {
                error_occured = true;
                error_message = e.toString();
            }
        }

*/ out.println("checkfinal"); }

}


Advertisement
View Answers

March 1, 2012 at 1:21 PM


1)page.jsp:

<%@ page language="java" %>
<HTML>
<FORM ENCTYPE="multipart/form-data" ACTION="../UploadServlet" METHOD=POST>
<center>
<table border="0" bgcolor=#ccFDDEE>
<tr>
<center><td colspan="2" align="center"><B>UPLOAD THE FILE</B><center></td>
</tr>
<tr><td colspan="2" align="center"> </td></tr>
<tr><td><b>Choose the file To Upload:</b></td>
<td><INPUT NAME="file" TYPE="file"></td>
</tr>
<tr><td colspan="2" align="center"> </td></tr>
<tr><td colspan="2" align="center"><input type="submit" value="Send File"> </td></tr>
<table>
</center>
</FORM>
</HTML>

2)UploadServlet.java:

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;

public class UploadServlet extends HttpServlet{ 
     public void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException {
     response.setContentType("text/html");
     PrintWriter out = response.getWriter();

    String saveFile="";
    String contentType = request.getContentType();
    if((contentType != null)&&(contentType.indexOf("multipart/form-data") >= 0)){
    DataInputStream in = new DataInputStream(request.getInputStream());
    int formDataLength = request.getContentLength();
    byte dataBytes[] = new byte[formDataLength];
    int byteRead = 0;
    int totalBytesRead = 0;
    while(totalBytesRead < formDataLength){
    byteRead = in.read(dataBytes, totalBytesRead,formDataLength);
    totalBytesRead += byteRead;
   }
    String file = new String(dataBytes);
    saveFile = file.substring(file.indexOf("filename=\"") + 10);
    saveFile = saveFile.substring(0, saveFile.indexOf("\n"));
    saveFile = saveFile.substring(saveFile.lastIndexOf("\\") + 1,saveFile.indexOf("\""));
    int lastIndex = contentType.lastIndexOf("=");
    String boundary = contentType.substring(lastIndex + 1,contentType.length());
    int pos;
    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;
    File ff = new File(saveFile);
    FileOutputStream fileOut = new FileOutputStream(ff);
    fileOut.write(dataBytes, startPos, (endPos - startPos));
    fileOut.flush();
    fileOut.close();
    out.println("You have successfully upload the file:"+saveFile);
    Connection connection = null;
    String connectionURL = "jdbc:mysql://localhost:3306/test";
    ResultSet rs = null;
    PreparedStatement psmnt = null;
    FileInputStream fis;
    try{
    Class.forName("com.mysql.jdbc.Driver").newInstance();
    connection = DriverManager.getConnection(connectionURL, "root", "root");
    File f = new File(saveFile);
    psmnt = connection.prepareStatement("insert into file(file_data) values(?)");
    fis = new FileInputStream(f);
    psmnt.setBinaryStream(1, (InputStream)fis, (int)(f.length()));
    int s = psmnt.executeUpdate();
    if(s>0){
    System.out.println("Uploaded successfully !");
    }
    else{
    System.out.println("Error!");
    }
    }
    catch(Exception e){
        e.printStackTrace();
        }
    }
  }
}


Related Tutorials/Questions & Answers:
 

 

 

DMCA.com