• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 784
  • Last Modified:

File Upload Session Bean

I have a working java bean under this statement. What i require is a workin session bean to upload a file from a client station to a server station. I am working on Websphere Studio Application Development tool from IBM and just want to know how i can do so using this tool. It wud be really helpful if some1 cud post the code for the same.

// THE CODE

import javax.servlet.http.HttpServletRequest;
import javax.servlet.ServletInputStream;
import java.util.Dictionary;
import java.util.Hashtable;
import java.io.PrintWriter;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;

public class FileUploadBean {

  private String savePath, filepath, filename, contentType;
  private Dictionary fields;

  public String getFilename() {
    return filename;
  }

  public String getFilepath() {
    return filepath;
  }

  public void setSavePath(String savePath) {
    this.savePath = savePath;
  }

  public String getContentType() {
    return contentType;
  }

  public String getFieldValue(String fieldName) {
    if (fields == null || fieldName == null)
      return null;
    return (String) fields.get(fieldName);
  }

  private void setFilename(String s) {
    if (s==null)
      return;

    int pos = s.indexOf("filename=\"");
    if (pos != -1) {
      filepath = s.substring(pos+10, s.length()-1);
      // Windows browsers include the full path on the client
      // But Linux/Unix and Mac browsers only send the filename
      // test if this is from a Windows browser
      pos = filepath.lastIndexOf("\\");
      if (pos != -1)
        filename = filepath.substring(pos + 1);
      else
        filename = filepath;
    }
  }

  private void setContentType(String s) {
    if (s==null)
      return;

    int pos = s.indexOf(": ");
    if (pos != -1)
      contentType = s.substring(pos+2, s.length());
  }

  public void doUpload(HttpServletRequest request) throws IOException {
    ServletInputStream in = request.getInputStream();

    byte[] line = new byte[128];
    int i = in.readLine(line, 0, 128);
    if (i < 3)
      return;
    int boundaryLength = i - 2;

    String boundary = new String(line, 0, boundaryLength); // -2 discards the newline character
    fields = new Hashtable();

    while (i != -1) {
      String newLine = new String(line, 0, i);
      if (newLine.startsWith("Content-Disposition: form-data; name=\"")) {
        if (newLine.indexOf("filename=\"") != -1) {
          setFilename(new String(line, 0, i-2));
          if (filename==null)
            return;
          //this is the file content
          i = in.readLine(line, 0, 128);
          setContentType(new String(line, 0, i-2));
          i = in.readLine(line, 0, 128);
          // blank line
          i = in.readLine(line, 0, 128);
          newLine = new String(line, 0, i);
          PrintWriter pw = new PrintWriter(new BufferedWriter(new
            FileWriter((savePath==null? "" : savePath) + filename)));
          while (i != -1 && !newLine.startsWith(boundary)) {
            // the problem is the last line of the file content
            // contains the new line character.
            // So, we need to check if the current line is
            // the last line.
            i = in.readLine(line, 0, 128);
            if ((i==boundaryLength+2 || i==boundaryLength+4) // + 4 is eof
              && (new String(line, 0, i).startsWith(boundary)))
              pw.print(newLine.substring(0, newLine.length()-2));
            else
              pw.print(newLine);
            newLine = new String(line, 0, i);

          }
          pw.close();

        }
        else {
          //this is a field
          // get the field name
          int pos = newLine.indexOf("name=\"");
          String fieldName = newLine.substring(pos+6, newLine.length()-3);
          // System.out.println("fieldName:" + fieldName);
          // blank line
          i = in.readLine(line, 0, 128);
          i = in.readLine(line, 0, 128);
          newLine = new String(line, 0, i);
          StringBuffer fieldValue = new StringBuffer(128);
          while (i != -1 && !newLine.startsWith(boundary)) {
            // The last line of the field
            // contains the new line character.
            // So, we need to check if the current line is
            // the last line.
            i = in.readLine(line, 0, 128);
            if ((i==boundaryLength+2 || i==boundaryLength+4) // + 4 is eof
              && (new String(line, 0, i).startsWith(boundary)))
              fieldValue.append(newLine.substring(0, newLine.length()-2));
            else
              fieldValue.append(newLine);
            newLine = new String(line, 0, i);
          }
          //System.out.println("fieldValue:" + fieldValue.toString());
          fields.put(fieldName, fieldValue.toString());
        }
      }
      i = in.readLine(line, 0, 128);
    } // end while
  }
}
0
X4nd3r
Asked:
X4nd3r
  • 4
  • 4
3 Solutions
 
bloodredsunCommented:
As you appear to be using HTTP to transfer files, have you not considered FileUpload from jakarta commons http://jakarta.apache.org/commons/fileupload/.

It is a robust and verstile method of transferring files from client to server over HTTP and has become pretty much the de facto standard and it might help you avoid re-inventing the wheel.
0
 
KuldeepchaturvediCommented:
jakarta common upload is easyy robust and way to go...

in your servlet have this method

public List doUpload(HttpServletRequest request) throws IOException,
            FileUploadException {

        //            Create a new file upload handler
        DiskFileUpload upload = new DiskFileUpload();

        //            Parse the request
        List /* FileItem */
        items = upload.parseRequest(request);
        return items;
    }

and then once you have items with you...

Iterator iter = items.iterator();
Hashtable ht = new Hashtable();
while (iter.hasNext()) {
FileItem item = (FileItem) iter.next();
if (!item.isFormField()) {
            try {
if (item.getName() != null && !item.getName().equals("")) {
InputStream in = item.getInputStream();
byte[] b=new byte[in.available()];
in.read(b);
//dump this byte array to your file
} else {
String name = item.getFieldName();
String value = item.getString();
ht.put(name, value);
}
}
0
 
X4nd3rAuthor Commented:
guys plz give me a few hours so that i can work upon them...thx for the quick replies...well said bloodredsun "re-inventing the wheel"  :D
0
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
bloodredsunCommented:
>>"re-inventing the wheel"

don't worry dude, we've all done it!

One of the nice things about EE is that you get the benefit of everyone elses mistakes when they've been repackaged as "experience"  and Kuldeep's given you a nice example ;-)
0
 
X4nd3rAuthor Commented:
thx guys, i completed it in a different fashion..anyways i wont take away your deserved points...before that i want to add a query of my own which i found as a proceeded in my project...can any1 post a code of how to read data from a .xls file (Microsoft Excel)
Preferably if any 1 of u bloodredsun or kuldeep can post it so it will be easier to distribute the points.
0
 
bloodredsunCommented:
>>can any1 post a code of how to read data from a .xls file (Microsoft Excel)

You'll need to use Jakarta POI, specifically HSSF http://jakarta.apache.org/poi/hssf/index.html.

e.g. Reading and Rewriting Workbooks

    POIFSFileSystem fs  =  new POIFSFileSystem(new FileInputStream("workbook.xls"));
    HSSFWorkbook wb = new HSSFWorkbook(fs);
    HSSFSheet sheet = wb.getSheetAt(0);
    HSSFRow row = sheet.getRow(2);
    HSSFCell cell = row.getCell((short)3);
    if (cell == null)
        cell = row.createCell((short)3);
    cell.setCellType(HSSFCell.CELL_TYPE_STRING);
    cell.setCellValue("a test");

    // Write the output to a file
    FileOutputStream fileOut = new FileOutputStream("workbook.xls");
    wb.write(fileOut);
    fileOut.close();
                   
0
 
X4nd3rAuthor Commented:
Thx a lot bloodredsun
But i am cofused as to how shud i import Jakarta POI in my session bean code...can it be done in the normal classes i import of java or is it sumthing different. Plz explain.
0
 
X4nd3rAuthor Commented:
bloodredsun plz explain how do i import the Jakarta POI into my session bean. I am unable to do so.
0
 
bloodredsunCommented:
you need to download the POI jar from jakarta, then import these packages into your class that will use it in the same way as you would for any 3rd party java classes. That's all
0

Featured Post

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

  • 4
  • 4
Tackle projects and never again get stuck behind a technical roadblock.
Join Now