JSP upload

I need to implement JSP upload page that upload files to the server. I want to know
if Java API can do that? or we need special component? I don't know how upload file
works internally. All I have now is the following upload form.
<FORM ACTION="process.jsp" METHOD="POST">
<INPUT TYPE="FILE" name="uploadFile">
<INPUT TYPE="SUBMIT"
</FORM>
please advise. thanks!!

Give you a complete FileUpload code based on servlet:
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class FileUpload extends HttpServlet {
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html>");
out.print("File upload success. <a href=\"/jspbook/files/");
out.print("\">Click here to browse through all uploaded ");
out.println("files.</a><br>");
ServletInputStream sis = request.getInputStream();
StringWriter sw = new StringWriter();
int i = sis.read();
for (;i!=-1&&i!='\r';i=sis.read()) {
sw.write(i);
sis.read(); // ditch '\n'
String delimiter = sw.toString();
int count = 0;
while(true) {
StringWriter h = new StringWriter();
int[] temp = new int[4];
temp[0] = (byte)sis.read();
temp[1] = (byte)sis.read();
temp[2] = (byte)sis.read();
h.write(temp[0]);
h.write(temp[1]);
h.write(temp[2]);
// read header
for (temp[3]=sis.read();temp[3]!=-1;temp[3]=sis.read()) {
if (temp[0] == '\r' &&
temp[1] == '\n' &&
temp[2] == '\r' &&
temp[3] == '\n') {
break;
h.write(temp[3]);
temp[0] = temp[1];
temp[1] = temp[2];
temp[2] = temp[3];
String header = h.toString();
int startName = header.indexOf("name=\"");
int endName = header.indexOf("\"",startName+6);
if (startName == -1 || endName == -1) {
break;
String name = header.substring(startName+6, endName);
if (name.equals("file")) {
startName = header.indexOf("filename=\"");
endName = header.indexOf("\"",startName+10);
String filename =
header.substring(startName+10,endName);
ServletContext sc =
request.getSession().getServletContext();
File file = new File(sc.getRealPath("/files"));
file.mkdirs();
FileOutputStream fos =
new FileOutputStream(
sc.getRealPath("/files")+"/"+filename);
// write whole file to disk
int length = 0;
delimiter = "\r\n"+delimiter;
byte[] body = new byte[delimiter.length()];
for (int j=0;j<body.length;j++) {
body[j] = (byte)sis.read();
// check it wasn't a 0 length file
if (!delimiter.equals(new String(body))) {
int e = body.length-1;
i=sis.read();
for (;i!=-1;i=sis.read()) {
fos.write(body[0]);
for (int l=0;l<body.length-1;l++) {
body[l]=body[l+1];
body[e] = (byte)i;
if (delimiter.equals(new String(body)))
break;
length++;
fos.flush();
fos.close();
if (sis.read() == '-' && sis.read() == '-')
break;
out.println("</html>");
public void doGet(HttpServletRequest request,HttpServletResponse response)
throws IOException, ServletException {
doPost(request, response);
}Of course you can also use jakarata's common fileupload,it's much easier.but I had not succeeded on my system.

Similar Messages

  • JSP Uploader on Linux Issue

    Hi.
    I have a JSP uploader. This works fine on Windows platforms. The linux version works well too, but only with text files. Any other file (.gpeg, .odt, .pdf etc) get corrupted in some way or another on uploading.
    Kindly look at the code involved and help me out. Thanks.
    <%@ page import="java.io.*, java.lang.*" %>
    <%
    out.println("Uploading your file. Please wait...");%><br><%
    String operatingSystemVersion = String.valueOf(System.getProperty("os.name"));
    FileOutputStream fileOut = null;
    if(operatingSystemVersion.startsWith("Linux"))
         String contentType = request.getContentType();
         String file = null;
         String saveFile = "";
         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;
              try
                   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=/" + 1);
                   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;
                   out.print("Boundary: " + boundaryLocation + "   ");
                   int startPos = ((file.substring(0, pos)).getBytes()).length;
                   out.print("startPos: " + startPos + "   ");
                   int endPos = ((file.substring(0, boundaryLocation)).getBytes()).length;
                   out.print("endPos: " + endPos + "   ");
                   //Specify the folder here that you want the file uploaded into
                   // Note that you need read/write permissions to that folder
                   String folder = "/home/arthur/uploads/";
                   fileOut = new FileOutputStream(folder + saveFile);
                   for(int i = 0; i < dataBytes.length; i++)
                        byte data = dataBytes;
                        fileOut.write(data);
                   fileOut.write(dataBytes, startPos, (endPos - startPos));
    //               out.print("Writing out OK");
                   out.print("flushing...");
                   fileOut.flush();
                   //     here </TD>
                   //     <meta HTTP-EQUIV="Refresh" content="5; URL=index.jsp">
                   //     <br>
              catch(Exception e)
                   out.print(e);
    else
         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;
              try
                   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;
                   // Specify the folder here that you want the file uploaded into
                   // Note that you need read/write permissions to that folder
                   String folder = "C:/Program Files/Apache Software Foundation/Tomcat5.5/webapps/upload/images/";
                   fileOut = new FileOutputStream(folder + saveFile);
                   fileOut.write(dataBytes, startPos, (endPos - startPos));
                   fileOut.flush();
                   fileOut.close();
                   %>
                        <meta HTTP-EQUIV="Refresh" content="5; URL=index.jsp">
                   <%
              catch(Exception e)
                   out.print(e);
              finally
                   try{fileOut.close();}catch(Exception err){}
    %>
    {code}

    I have acquired Apache file upload and modified upload.jsp and this is how it looks:
    <%@ page import="java.io.*, java.lang.*, org.apache.commons.io.*, org.apache.commons.fileupload.*" %>
    <%
              out.println("Uploading your file. Please wait...");%><br><%
              DiskFileItemFactory factory = new DiskFileItemFactory();
            // maximum size that will be stored in memory
            factory.setSizeThreshold(4096);
            // the location for saving data that is larger than getSizeThreshold()
            factory.setRepository(new File("C:/tmp"));
            ServletFileUpload upload = new ServletFileUpload(factory);
            // maximum size before a FileUploadException will be thrown
            upload.setSizeMax(1000000);
            List fileItems = upload.parseRequest(req);
            // assume we know there are two files. The first file is a small
            // text file, the second is unknown and is written to a file on
            // the server
            Iterator i = fileItems.iterator();
            String comment = ((FileItem)i.next()).getString();
            FileItem fi = (FileItem)i.next();
            // filename on the client
            String fileName = fi.getName();
            // save comment and filename to database
            // write the file
            fi.write(new File("C:/", fileName));
    %>However, Tomcat complains that
    HTTP Status 500 -
    type Exception report
    message
    description The server encountered an internal error () that prevented it from fulfilling this request.
    exception
    org.apache.jasper.JasperException: Unable to compile class for JSP:
    An error occurred at line: 4 in the jsp file: /upload.jsp
    DiskFileItemFactory cannot be resolved to a type
    1: <%@ page import="java.io.*, java.lang.*, org.apache.commons.io.*, org.apache.commons.fileupload.*" %>
    2: <%
    3: out.println("Uploading your file. Please wait...");%><br><%
    4: DiskFileItemFactory factory = new DiskFileItemFactory();
    5:
    6: // Set factory constraints
    7: factory.setSizeThreshold(yourMaxMemorySize);
    An error occurred at line: 4 in the jsp file: /upload.jsp
    DiskFileItemFactory cannot be resolved to a type
    1: <%@ page import="java.io.*, java.lang.*, org.apache.commons.io.*, org.apache.commons.fileupload.*" %>
    2: <%
    3: out.println("Uploading your file. Please wait...");%><br><%
    4: DiskFileItemFactory factory = new DiskFileItemFactory();
    5:
    6: // Set factory constraints
    7: factory.setSizeThreshold(yourMaxMemorySize);
    An error occurred at line: 7 in the jsp file: /upload.jsp
    yourMaxMemorySize cannot be resolved
    4: DiskFileItemFactory factory = new DiskFileItemFactory();
    5:
    6: // Set factory constraints
    7: factory.setSizeThreshold(yourMaxMemorySize);
    8: factory.setRepository(new File("C:/Documents and Settings/Arthur/Desktop/"));
    9:
    10: // Create a new file upload handler
    An error occurred at line: 11 in the jsp file: /upload.jsp
    ServletFileUpload cannot be resolved to a type
    8: factory.setRepository(new File("C:/Documents and Settings/Arthur/Desktop/"));
    9:
    10: // Create a new file upload handler
    11: ServletFileUpload upload = new ServletFileUpload(factory);
    12:
    13: // Set overall request size constraint
    14: upload.setSizeMax(yourMaxRequestSize);
    An error occurred at line: 11 in the jsp file: /upload.jsp
    ServletFileUpload cannot be resolved to a type
    8: factory.setRepository(new File("C:/Documents and Settings/Arthur/Desktop/"));
    9:
    10: // Create a new file upload handler
    11: ServletFileUpload upload = new ServletFileUpload(factory);
    12:
    13: // Set overall request size constraint
    14: upload.setSizeMax(yourMaxRequestSize);
    An error occurred at line: 14 in the jsp file: /upload.jsp
    yourMaxRequestSize cannot be resolved
    11: ServletFileUpload upload = new ServletFileUpload(factory);
    12:
    13: // Set overall request size constraint
    14: upload.setSizeMax(yourMaxRequestSize);
    15:
    16: // Parse the request
    17: List /* FileItem */ items = upload.parseRequest(request);
    An error occurred at line: 17 in the jsp file: /upload.jsp
    List cannot be resolved to a type
    14: upload.setSizeMax(yourMaxRequestSize);
    15:
    16: // Parse the request
    17: List /* FileItem */ items = upload.parseRequest(request);
    18: %>
    Stacktrace:
         org.apache.jasper.compiler.DefaultErrorHandler.javacError(DefaultErrorHandler.java:85)
         org.apache.jasper.compiler.ErrorDispatcher.javacError(ErrorDispatcher.java:330)
         org.apache.jasper.compiler.JDTCompiler.generateClass(JDTCompiler.java:435)
         org.apache.jasper.compiler.Compiler.compile(Compiler.java:298)
         org.apache.jasper.compiler.Compiler.compile(Compiler.java:277)
         org.apache.jasper.compiler.Compiler.compile(Compiler.java:265)
         org.apache.jasper.JspCompilationContext.compile(JspCompilationContext.java:564)
         org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:299)
         org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:315)
         org.apache.jasper.servlet.JspServlet.service(JspServlet.java:265)
         javax.servlet.http.HttpServlet.service(HttpServlet.java:803)
    note The full stack trace of the root cause is available in the Apache Tomcat/5.5.23 logs.
    Apache Tomcat/5.5.23Any help?

  • Plz help in jsp upload

    Exam.jsp
    <html>
      <body>
            <form action="Exam1.jsp"  enctype="multipart/form-data">
          <input type="text" name="s1"><br>
          <input type="file" name="f1"><br>
          <input type="text" name="ans1"><br>
          <input type="text" name="num1"><br>
              <input type="submit" value="submit"> 
            </form>
        </body>
    </html>Exam1.jsp
    <%@page import="java.io.*"%>
    <%@page import="java.sql.*"%>
    <%
    String s2 = request.getParameter("s1");
    String s3 = request.getParameter("ans1");
    String s4=request.getParameter("num1");
    out.print(s2);
    out.print(s3);
    out.print(s4);
    String contentType = request.getContentType();
    System.out.println("Content type is :: " +contentType);
    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);
    String 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;
    saveFile = "C:\\Documents and Settings\\Administrator\\jspexm\\sri123\\web\\uploads\\" + saveFile;
    FileOutputStream fileOut = new FileOutputStream(saveFile);
    //fileOut.write(dataBytes);
    fileOut.write(dataBytes, startPos, (endPos - startPos));
    fileOut.flush();
    fileOut.close();
    out.println("File saved as " +saveFile);
    is this code correct
    Please help
    {code}                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

    hi
    thanks for reply
    iam not geting Exceptions
    i am unable to print the values from Exam.jsp
    using this in Exam1.jsp
    String s2 = request.getParameter("s1");
    String s3 = request.getParameter("ans1");
    String s4=request.getParameter("num1");
    out.print(s2);
    out.print(s3);
    out.print(s4);while uploding the file

  • Using Jsp upload Image

    I m using jdbc 2.0 . The image is stored in the LongRaw data type . Now without getbinarystream i want to get that data and display as an image. There is a oracle.jdbc.* package which provides getRaw() method .But i am facing problems in it . Can any one help me ? Please help me it is very urgent.

    You have to write file upload bean for that there are many resources in weg for that search in google

  • JSP that converts office extensions to pdf and then upload them

    Hi there !
    Im trying to convert office extensions ( .xls, .ppt, etc) to pdf and then upload the resulting file to a server .
    currectly im using the upload solution posted by the user anna_DRA here : http://forums.sun.com/thread.jspa?threadID=672874
    and as for the conversion im using a solution which uses OpenOffice's lib to do the conversion.I'm going to post the codes of my JSP and my HTML ( which just contains the form to get the file to be converted and uploaded).
    observation: the point which is giving me headaches is how to get the file sent by my form, convert it into a File object, use my conversion tool and then deliver it to my upload tool so it can be stored.... i cant seem to get the File object from the request object ( tried getattribute and it returns null....) .
    observation':I do know about and how to use MVC but my boss asked me to make this work with just one JSP or a JSP and a HTML.
    index.html :
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
    <title>Upload test</title>
    </head>
    <body>
    <form enctype="multipart/form-data" action="/WSPdfConversion1.1/Conversion.jsp" method=POST>
    <input type="file" name = "FileUp">
    <input type="submit" value="Enviar"/>
    </form>
    </body>
    </html>Conversion.jsp :
    upload portion:
    MultipartFormDataRequest mrequest = new MultipartFormDataRequest(request);
    OpenOfficeConnection OpenOfficeConnection = new SocketOpenOfficeConnection(8100);
    String newName = "";
    Hashtable files = mrequest.getFiles();
    UploadFile file = (UploadFile) files.get("FileUp");//Give name u r given in the previous page.
    String fileName = file.getFileName();
    upBean.store(mrequest, "FileUp");conversion portion:
    OpenOfficeConnection OpenOfficeConnection = new SocketOpenOfficeConnection(8100);
    try {
        OpenOfficeConnection.connect();
    } catch (ConnectException e) {
        e.printStackTrace();
    File inputFile = new File("C:\\Users\\thiago\\Documents\\"+fileName);
    for(int i = 0; i <= fileName.length() - 4; i++){
        String s = ""+fileName.charAt(i);
        newName = newName.concat(s);
    File outputFile = new File("C:\\Users\\thiago\\Documents\\"+newName+".pdf");
    //convert the spreadsheet
    DocumentConverter ExcelToPDFConverter = new OpenOfficeDocumentConverter(OpenOfficeConnection);
    ExcelToPDFConverter.convert(inputFile, outputFile);
    OpenOfficeConnection.disconnect();Both work just ok when separated but i cant get both to work together....
    Any help is much appreciated!!!
    Thanks in advance
    Edited by: thiagocbalducci on Mar 24, 2010 12:07 PM
    Edited by: thiagocbalducci on Mar 24, 2010 12:09 PM

    Hello TSN,
    Test Screen Name wrote:
    Picking just one point: PDF -> EPS -> PDF. This could not possibly do more than one page, because EPS is absolutely by definition a single page format. Therefore you must choose a page when exporting PDF to EPS.
    Thanks for your response.
    I was thinking Microsoft... which has allowed multi-page eps files for years. But you're correct, this is normally an unsupported .eps format.
    I solved the problem over the weekend by doing the following:
    1) I removed the suspect OTF font family but despite doing so, the folder still had two 'corrupted' but unused copies of an italic font. They refused to remove so I had to boot into Win7 SAFE mode to remove.
    2) After complete removal of the OTF font family. I reinstalled the OTF font *BUT* only from a different repository (oddly, this other OTF font set is slightly larger per font).
    3) Once installed, I tested with Flare, published and uploaded to Crocodoc SUCCESSFULLY. Yeah!
    I don't have anymore time to test but the questions remain, such as, was it one or more of the following issues:
    a) Flare has a problem handling some OTF fonts or cannot error correct (the way other programs do) for marginal fonts or font errors?
    b) Was it the two corrupted fonts in the Windows/fonts folder?
    c) Was it the slightly different OTF fonts that I am no longer using?
    Take care

  • Error in uploading excel file using Java pages

    Hello,
    We are using oracle ERP (R12.1.1) and we have developed one JSP page to upload an excel.
    After selecting the excel and browse button is clicked we are gettign the OLE stream error when the excel file is .csv or .xlsx. There is no issue with .xls excel files. For loading the excel data to custom table we are using the "jxl-2.6.jar".
    Can we get higher version of "jxl-2.6.jar to support CSV upload?
    Thanks.

    Are you Registered this jsp upload page to EBS before test?
    You have to register the page to EBS first.
    Regards,
    Dilip

  • How to get the pull path name from a file upload window

    Hello everyone!
    I have encountered the following problem with the following JSP code:
    <form method="post" action="filename.jsp">
    Upload JAVA program:
    <input type=file size=20 name="fname" accept="java">
    <input type=submit value="go">
    </form>
    <%
    String s = "";
    if (request.getParameter("fname") != null)
    s = request.getParameter("fname")
    %>
    The value of s is alway the filename. However I want to get the full path in addition to the filename, so that I can read the file. Does anyone know how to get the pull name of the file?
    thanks a lot in advance,

    Dear Sir,
    thanks a lot for your reply. Please let me explain what I intended to do: I want to upload a file from the local machine and then read the content of the file. Therefore I need to the fullpath of the filename like /var/local/file.java instead of file.java. The latter is what I got.
    The problem I have with your code is that the function like "request.getServerScheme()" is not recognized. Maybe is it because I didn't install servelet package? I only installed javax package btw. Also my application runns on Tomcat server if this could give you some information. The error message I had is as follows:
    org.apache.jasper.JasperException: Unable to compile class for JSP
    An error occurred at line: 36 in the jsp file: /addExercise.jsp
    Generated servlet error:
    [javac] Compiling 1 source file
    /usr/local/jakarta-tomcat-5.0.12/work/Catalina/localhost/tutor/org/apache/jsp/addExercise_jsp.java:133: cannot resolve symbol
    symbol : method getServerScheme ()
    location: interface javax.servlet.http.HttpServletRequest
    url = request.getServerScheme()
    ^
    An error occurred at line: 36 in the jsp file: /addExercise.jsp
    Generated servlet error:
    /usr/local/jakarta-tomcat-5.0.12/work/Catalina/localhost/tutor/org/apache/jsp/addExercise_jsp.java:136: cannot resolve symbol
    symbol : method getServerScheme ()
    location: interface javax.servlet.http.HttpServletRequest
    + ((("http".equals(request.getServerScheme()) && request.getServerPort() != 80)
    ^
    An error occurred at line: 36 in the jsp file: /addExercise.jsp
    Generated servlet error:
    /usr/local/jakarta-tomcat-5.0.12/work/Catalina/localhost/tutor/org/apache/jsp/addExercise_jsp.java:137: cannot resolve symbol
    symbol : method getServerScheme ()
    location: interface javax.servlet.http.HttpServletRequest
    ||("https".equals(request.getServerScheme()) && request.getServerPort() != 443))
    ^
    An error occurred at line: 36 in the jsp file: /addExercise.jsp
    Generated servlet error:
    /usr/local/jakarta-tomcat-5.0.12/work/Catalina/localhost/tutor/org/apache/jsp/addExercise_jsp.java:139: cannot resolve symbol
    symbol : method getServletConfig ()
    location: interface javax.servlet.http.HttpServletRequest
    + "/" + request.getServletConfig().getServletName()
    ^
    An error occurred at line: 36 in the jsp file: /addExercise.jsp
    Generated servlet error:
    /usr/local/jakarta-tomcat-5.0.12/work/Catalina/localhost/tutor/org/apache/jsp/addExercise_jsp.java:140: cannot resolve symbol
    symbol : variable path
    location: class org.apache.jsp.addExercise_jsp
    + "/" + path
    ^
    5 errors
         org.apache.jasper.compiler.DefaultErrorHandler.javacError(DefaultErrorHandler.java:128)
         org.apache.jasper.compiler.ErrorDispatcher.javacError(ErrorDispatcher.java:351)
         org.apache.jasper.compiler.Compiler.generateClass(Compiler.java:413)
         org.apache.jasper.compiler.Compiler.compile(Compiler.java:453)
         org.apache.jasper.compiler.Compiler.compile(Compiler.java:437)
         org.apache.jasper.JspCompilationContext.compile(JspCompilationContext.java:555)
         org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:291)
         org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:301)
         org.apache.jasper.servlet.JspServlet.service(JspServlet.java:248)
         javax.servlet.http.HttpServlet.service(HttpServlet.java:856)

  • Getting extra things in the uploaded file by flex file upload

    Hi,
    I am working on a application where I am using adobe flex. I
    have a requirement wher I have to upload file to the server. System
    allows user to browse file from local machine and flex uploads it
    to the server.
    Now there is a upload url, its a jsp page which gets
    mutipart/form-data content from the request, opens an outputstream
    and writes the content of the inputstrem to the file.
    fileUpload.mxml
    quote:
    <?xml version="1.0" encoding="utf-8"?>
    <mx:Application xmlns:mx="
    http://www.adobe.com/2006/mxml"
    layout="vertical" creationComplete="initApp()">
    <mx:Script>
    <![CDATA[
    import mx.controls.Alert;
    import mx.utils.ObjectUtil;
    import flash.events.*;
    import flash.net.FileReference;
    import flash.net.URLRequest;
    private var fileRef:FileReference;
    private function initApp():void {
    fileRef = new FileReference();
    fileRef.addEventListener(Event.CANCEL, traceEvent);
    fileRef.addEventListener(Event.COMPLETE, completeEvent);
    fileRef.addEventListener(Event.SELECT, selectEvent);
    fileRef.addEventListener(IOErrorEvent.IO_ERROR, traceEvent);
    fileRef.addEventListener(Event.OPEN, traceEvent);
    fileRef.addEventListener(ProgressEvent.PROGRESS,
    progressEvent);
    fileRef.addEventListener(SecurityErrorEvent.SECURITY_ERROR,
    traceEvent);
    private function traceEvent(event:Event):void {
    var tmp:String = "================================\n";
    //ta.text += tmp + event.type + " event:" +
    mx.utils.ObjectUtil.toString(event) + "\n" ;
    //ta.verticalScrollPosition += 20;
    private function ioErrorEvent(event:IOErrorEvent):void{
    Alert.show("IOError:" + event.text);
    traceEvent(event);
    private function selectEvent(event:Event):void{
    btn_upload.enabled = true;
    traceEvent(event);
    filename.text = fileRef.name;
    progressBar.setProgress(0, 100);
    progressBar.label = "Loading 0%";
    private function progressEvent(event:ProgressEvent):void {
    progressBar.setProgress(event.bytesLoaded,
    event.bytesTotal);
    traceEvent(event);
    private function completeEvent(event:Event):void {
    progressBar.label = "Complete.";
    filename.text += " uploaded";
    traceEvent(event);
    btn_upload.enabled = false;
    btn_cancel.enabled = false;
    private function uploadFile(endpoint:String):void {
    var param:String = "author=" + ti_author.text;
    var req:URLRequest = new URLRequest(endpoint);
    req.method = URLRequestMethod.POST;
    fileRef.upload(req, param, false);
    progressBar.label = "Uploading...";
    btn_cancel.enabled = true;
    ]]>
    </mx:Script>
    <mx:Panel title="Flex 2 File Uploading Demo" width="100%"
    height="100%" >
    <mx:Form>
    <mx:FormItem label="Upload URL:">
    <mx:TextInput editable="false" id="uploadURL"
    width="100%" text="
    http://localhost/flexApp/jsps/upload.jsp"
    enabled="true" />
    </mx:FormItem>
    <mx:FormItem label="Selected File:">
    <mx:Label id="filename"/>
    </mx:FormItem>
    <mx:FormItem label="Upload By:">
    <mx:TextInput id="ti_author" text="Author" />
    </mx:FormItem>
    <mx:FormItem direction="horizontal" width="100%">
    <mx:Button width="80" label="Browse"
    click="fileRef.browse()" />
    <mx:Button width="80" label="Upload" id="btn_upload"
    enabled="false" click="uploadFile(uploadURL.text)" />
    <mx:Button width="80" label="Cancel" id="btn_cancel"
    enabled="false" click="fileRef.cancel()" />
    </mx:FormItem>
    <mx:HRule width="100%" tabEnabled="false"/>
    <mx:FormItem label="Progress:">
    <mx:ProgressBar id="progressBar" mode="manual" />
    </mx:FormItem>
    </mx:Form>
    </mx:Panel>
    </mx:Application>
    test.jsp page
    quote:
    InputStream is = null;
    BufferedInputStream bis = null;
    BufferedOutputStream bos = null;
    try {
    System.out.println("request.getContentType()...." +
    request.getContentType());
    is = request.getInputStream();
    bis = new BufferedInputStream(is);
    bos = new BufferedOutputStream(new FileOutputStream(new
    File("d:/naseem.txt")));
    int i=0;
    while ((i = bis.read())!=-1) {
    bos.write(i);
    bos.flush();
    catch(Exception e){
    e.printStackTrace();
    finally{
    try{
    if(bos!=null && is!=null && bis!=null){
    bos.close();is.close();bis.close();
    }catch(Exception e){e.printStackTrace();}
    Above jsp writes the content of browsed file to d:/naseem.txt
    Problem which I am facing is besides the actual content, it
    also write something else.
    Actual file:
    quote:
    My Text
    upload txt file which I got: naseem.txt
    quote:
    ------------cH2ei4GI3ae0KM7cH2GI3ei4ae0cH2
    Content-Disposition: form-data; name="Filename"
    test.txt
    ------------cH2ei4GI3ae0KM7cH2GI3ei4ae0cH2
    Content-Disposition: form-data; name="author=Author";
    filename="test.txt"
    Content-Type: application/octet-stream
    My Text
    ------------cH2ei4GI3ae0KM7cH2GI3ei4ae0cH2
    Content-Disposition: form-data; name="Upload"
    Submit Query
    ------------cH2ei4GI3ae0KM7cH2GI3ei4ae0cH2--
    My question is how do I remove these content-disposition,
    content type i.e., extra things from my file. I need only content
    to be written in the file.
    Regards,
    Naseem

    Hi Naseem,
    You need a multipart request parsing utility. Check commons-fileupload for example.

  • Upload csv file data to sql server tables

    Hi all,
    I want clients to upload csv file from their machines to the server.
    Then the program should read all the data from the csv file and do a bulk insert into the SQL Server tables.
    Please help me of how to go about doing this.
    Thanx in advance.....

    1) Use a multipart form with input type="file" to let the client choose a file.
    2) Get the binary stream and put it in a BufferedReader.
    3) Read each line and map it to a DTO and add each DTO to a list.
    4) Persist the list of DTO's.
    Helpful links:
    1) http://www.google.com/search?q=jsp+upload+file
    2) http://www.google.com/search?q=java+io+tutorial
    3) http://www.google.com/search?q=java+bufferedreader+readline
    4) http://www.google.com/search?q=jdbc+tutorial and http://www.google.com/search?q=sql+tutorial

  • Upload files using usp

    I have a html form where the user browse for a file and submit the form. Then it calls a JSP page to upload the file on to the database. Pls help me to do this.

    Not one to spoon-feed, but here's something to get you started. I don't know where I got this code from so I can't credit anyone....
    The HTML form for browsing for the file:
    <form action="upload.jsp" method="POST" enctype="multipart/form-data">
         <!-- enctype="multipart/form-data" -->
         <input type="file" name="theFile"/>
         <br>
         <input type="submit"/>
    </form>The JSP (upload.jsp) for receiving the form:
    <!-- upload.jsp -->
    <%@ page import="java.io.*" %>
    <%
         String contentType = request.getContentType();
         System.out.println("Content type is :: " +contentType);
         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);
              String saveFile = file.substring(file.indexOf("filename=\"") + 10);
              //out.print("FileName:" + saveFile.toString());
              saveFile = saveFile.substring(0, saveFile.indexOf("\n"));
              //out.print("FileName:" + saveFile.toString());
              saveFile = saveFile.substring(saveFile.lastIndexOf("\\") + 1,saveFile.indexOf("\""));
              //out.print("FileName:" + saveFile.toString());
              //out.print(dataBytes);
              int lastIndex = contentType.lastIndexOf("=");
              String boundary = contentType.substring(lastIndex + 1,contentType.length());
              //out.println(boundary);
              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;
              FileOutputStream fileOut = new FileOutputStream(saveFile);
              //fileOut.write(dataBytes);
              fileOut.write(dataBytes, startPos, (endPos - startPos));
              fileOut.flush();
              fileOut.close();
              out.println("File saved as " +saveFile);
    %>The file should get created in your system32 directory; you can change the path to save elsewhere.
    I think there are shortcomings to this code , for example, if you put other fields in the form, I don't think it'll work. But it should be good enough for a simple upload or atleast to get you started with this.

  • How-to navigate to a JSF JSP that is nested in a sub-directory???

    Here is the navigation rule from faces-config.xml
    <navigation-rule>
    <from-view-id>/index.jsp</from-view-id>
    <navigation-case>
    <from-outcome>next</from-outcome>
    <to-view-id>/upload/uploadImage.jsp</to-view-id>
    </navigation-case>
    </navigation-rule>
    Here is the web content directory structure
    /upload/upLoadImage.jsp
    index.jsp
    The result is:
    404 not found
    jsp error
    Request URI:/fileupload-ViewController-context-root/upload/uploadImage.jsp
    Exception:
    OracleJSP:java.io.FileNotFoundException: /upload/uploadImage.jsp
    How do I fix the navigation or does everything have to be at the same directory level?
    Regards,
    Al Malin

    Does everything have to be at the same directory level?
    The <to-view-id/> JSP/html is not required to be at the same directory level as <from-view-id/>
    Is the JSP /upload/upLoadImage.jsp and not /upload/uploadImage.jsp?

  • Uploading File Question

    How would I go about writing a JSP that allows a user to upload a file and then the JSP stores the file in a specific directory?

    Try
    http://www.servlets.com/cos/index.html
    It's an Servlet, JSP Upload Package by oreilly. MultiPartParser and MultiRequestParser are suitable for the thing you want to do.
    It's very easy and has some examples. I used it for a File Management system at my university!!

  • Multiple SQL Update within Parent Query

    I am tring to extract an image from within a MS SQL image field,
    opening the image using JAI, getting the src.getWidth() & src.getHeight
    () of each item within the database, and then writing the width and
    height back into the database. Everything works except when I goto
    write the values into the database - the page (when loading) continues
    to work and work and work until I restart the tomcat service. I do not
    understand why this would occur, and what is even stranger - I have
    very similar code i used for resizing images in the database into a
    thumbnail - display and original file sizes using a similar approach...
    and that works with out a problem...
    I have tried the code with out the inner update query - it works. I
    tried with just the selection of a single specific item in the first
    query and that works, but when I try multiple updates the second query
    appears to stall.
    The code is as follows.:
    <%@ page language="java" import="javax.servlet.*,javax.servlet.http.*,java.io.*,java.util.*,java.sql.*,javax.media.jai.*,java.awt.*,java.awt.image.*,java.awt.Graphics.*,java.awt.geom.*,java.awt.image.renderable.*,javax.media.jai.widget.*,com.jspsmart.upload.*,java.net.*,com.sun.media.jai.codec.*"%>
    <jsp:useBean id="mySmartUpload" scope="page" class="com.jspsmart.upload.SmartUpload" />
    <%
         // Variables
         int count=0;
         int width                                             = 0;
         int height                                             = 0;
         String vFileName                                   = "";
         String vFileExt                                        = "";
         String vFileID                                        = "";
         String format                                        = "0";
         // Connect to the database
         Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");
         Connection con = DriverManager.getConnection("jdbc:microsoft:sqlserver://206.152.227.62:1433;DatabaseName=WWWBBD;User=wwwbbd;Password=bbd1412");
         //Create the statement
         Statement sqlGetPics                              = con.createStatement();
         Statement sqlUpdate                                   = con.createStatement();
         //build the query
         String qryGetPics                                   = "SELECT TOP 5 FileID, FileExt, FileName, AdjFile = CASE WHEN FullFile IS NULL THEN Display ELSE FullFile END FROM FileStore WHERE (UPPER(FileExt) = '.JPG' OR UPPER(FileExt) = '.TIF' OR UPPER(FileExt) = '.GIF' OR UPPER(FileExt) = '.BMP') AND (NOT Display IS NULL OR NOT FullFile IS NULL)";
         //execute the query
         ResultSet rsGetPics                                   = sqlGetPics.executeQuery(qryGetPics);
         // Initialization
         SmartUpload uploader                              = new SmartUpload();
         uploader.initialize(getServletConfig(),request,response);
         mySmartUpload.initialize(getServletConfig(), request, response);
         // Upload
         mySmartUpload.upload();
         while (rsGetPics.next()) {
              vFileID                                             = rsGetPics.getString("FileID");
              vFileExt                                        = rsGetPics.getString("FileExt");
              vFileName                                        = rsGetPics.getString("FileName") + vFileExt;
              width                                             = 0;
              height                                             = 0;
              uploader.fieldToFile(rsGetPics, "AdjFile", "/upload/" + vFileName);
              if (vFileExt.equalsIgnoreCase(".JPG") || vFileExt.equalsIgnoreCase(".JPEG"))
                   format                                        = "JPEG";
              else if (vFileExt.equalsIgnoreCase(".TIF") || vFileExt.equalsIgnoreCase(".TIFF"))
                   format                                        = "TIFF";
              else if (vFileExt.equalsIgnoreCase(".GIF"))
                   format                                        = "JPEG";
              else if (vFileExt.equalsIgnoreCase(".BMP"))
                   format                                        = "BMP";
              else
                   format                                        = "0";
              // update the width & height
              if (format != "0")
                   try
                        //Opens the image
                        RenderedImage src                    = JAI.create("fileload","d:\\servers\\tomcat\\webapps\\jsp\\upload\\" + vFileName);
                        width                                   = src.getWidth();
                        height                                   = src.getHeight();
                        java.io.File imageFile               = new java.io.File("d:\\servers\\tomcat\\webapps\\jsp\\upload\\" + vFileName);
                        InputStream is                         = new FileInputStream(imageFile);
                        //build the query
                        String qryUpdate                    = "UPDATE FileStore SET Width = " + width + ", Height = " + height + " WHERE FileID = " + vFileID;
                        //execute the query
                        ResultSet rsUpdate                    = sqlUpdate.executeQuery(qryUpdate);
                        %>[<%=width%>x<%=height%>:<%=vFileID%>:<%=qryUpdate%>]<BR><%
                   catch(Exception e)
                        {out.println("An error occurs : " + e.toString());}               
              count++;          
         //rsUpdate.close();
         sqlUpdate.close();
    %>
    <HTML>
    <HEAD>
         <TITLE>Repair Files</TITLE>
    </HEAD>
    <BODY>
    <%=count%> files updated in the database.
    </BODY>
    </HTML>

    BTW - I also tried this with a prepared statment query... no good.

  • Use of input  type="file"

    Hellow
    How can I use the HTML tag <input type="file" > in jsp/servlets ?
    how can I got the file and saving it?

    Take a look at this page: http://search.java.sun.com/search/java/?qt=jsp+upload&x=39&y=6 - it is a search page and you can use it to find whether or not anyone has asked the question you have before. Often you will find that the question you have asked has been asked before, sometimes as much as 29000 times. It is quicker than asking a question for the first time because you don't have to wait for replies. - they are already there. I also believe that if you don't know understand search engines you are unlikely to understand Java.
    To help with your search you may want to know that the "file" input type creates a Multipart request and that the term "com.oreilly.servlets" may well be relevant too.

  • HT3771 I Have a Kyocera FS-C2026MFP printer/scanner. How can I only pint the document in Black. I cannot work out how to not print in colour to save the inks!!

    I Have a Kyocera FS-C2026MFP printer/scanner. How can I only pint the document in Black. I cannot work out how to not print in colour to save the inks!!

    Welcome to Apple Support Communities. We're users here and do not speak for "Apple Inc." or "Kyocera Inc."
    http://usa.kyoceradocumentsolutions.com/americas/jsp/upload/resource/25359/0/Mac Driver3SoftwareGuide1.1.pdf
    On the printer driver documentation, Page 5, in the Imaging setting, although the options are not specifically shown, there should be an option on that screen of the print driver to click and select "B/W" or 'black and white' or 'grayscale' or 'monochrome' as Print Mode rather than the "Full Color" option shown in the illustration below.
    You access these settings once you have selected 'Print' from an app.
    If necessary, you might need to click on the 'Down arrow' button next to the printer name (OS X 10.6), or 'Show Details' button at the bottom of the print dialog box (OS X 10.8) to see additional settings.

Maybe you are looking for