commons-user mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From Dakota Jack <dakota.j...@gmail.com>
Subject Re: uploading image?
Date Tue, 21 Dec 2004 15:30:24 GMT
On Tue, 21 Dec 2004 14:02:00 +0900, jackie <jackie@a2suite.com> wrote:
> Hello every one!
> 
> I would like to know how to upload an image and be able to display it in the
> original page where the upload form is there.
> 

First, separate uploading and displaying.  They are totally separate. 
The fact that you are displaying an image you uploaded is irrelevant. 
I presume that you know how to display an image with <img
src='whatever'> and will, therefore, not address that aspect.

Second, your decision to use commons-upload is a good one, I think,
and the only one really relevant to this list.  I too use
commons-upload and get great results.  I have built an entire
application around commons-upload.  So, my use won't be a lot of help.
 I will give you and overview of what I did.

I have a facade Upload class that takes care of store types (zip,
folder, database), what types of files (gif, exe, doc, etc.) are
allowed and/or disallowed, listeners (for upload notifications to the
client, etc.), and upload management (file size, number of files,
etc.).

I use Struts, but not the Struts file upload application, so I have an
UploadAction which sets an UploadListener in the session, sets the
store type, sets the store information, e.g. if a folder where the
folder is, sets a temp directory for parsing, adds the upload listener
to the Upload class,  and creates an UploadMultipartFormDataRequest
object with request, upload file size limits, encoding type, and
listeners as parameters. The "guts" of this class is a
CrackwillowMulitpart which is an implementation imploying the
CommonsDiskFileUpload and CommonsFileItem.  I do things like the
following, to give you and idea.


public class CrackWillowOutputStream
    extends CommonsDeferredFileOutputStream {
  private Vector  listeners;
  private boolean isFormField;

  public CrackWillowOutputStream(int     threshold,
                                 File    outputFile,
                                 Vector  listeners,
                                 boolean isFormField) {
    super(threshold, outputFile);
    this.listeners = listeners;
    this.isFormField = isFormField;
  }

  public void write(byte data0[], int i, int j)
      throws IOException {
    super.write(data0, i, j);
    if(listeners != null && !this.isFormField) {
      for(int k = 0; k < listeners.size(); k++) {
        UploadListener ul = (UploadListener)listeners.elementAt(k);
        ul.dataRead(j);
      }
    }
  }
}

  public CrackWillowFileItem(String  fieldName,
                             String  contentType,
                             boolean isFormField,
                             String  name,
                             int     threshold,
                             File    tempDir,
                             Vector  listeners,
                             int     totalSize) {
    this.fieldName   = fieldName;
    this.contentType = contentType;
    this.isFormField = isFormField;
    this.name        = name;
    this.threshold   = threshold;
    this.tempDir     = tempDir;
    this.listeners   = listeners;
    this.totalSize   = totalSize;
  }

  public void delete() {
    this.data = null;
    File file = getStoreLocation();
    if(file != null && file.exists()) {
      file.delete();
    }
  }

  protected void finalize() {
    File file = cwos.getFile();
    if(file != null && file.exists()) {
      file.delete();
    }
  }

  public byte[] get() {
    if(cwos.isInMemory()) {
      if(data == null) {
        data = cwos.getData();
      }

      return data;
    }

    byte fisData[] = new byte[(int)getSize()];
    FileInputStream fis = null;
    try {
      fis = new FileInputStream(cwos.getFile());
      fis.read(fisData);
    } catch(IOException ioe) {
      fisData = null;
    } finally {
      if(fis != null) {
        try {
          fis.close();
        } catch(IOException ioe1) { }
      }
    }
    return fisData;
  }

  public String  getContentType() {
    return contentType;
  }

  public String  getFieldName() {
    return fieldName;
  }

  public InputStream getInputStream()
      throws IOException {
    if(!this.cwos.isInMemory()) {
      return new FileInputStream(cwos.getFile());
    }

    if(data == null) {
      data = this.cwos.getData();
    }

    return new ByteArrayInputStream(data);
  }

  public String getName() {
    return name;
  }

  public OutputStream getOutputStream()
      throws IOException {
    if(cwos == null) {
      File outputFile = getTempFile();

      this.cwos = new CrackWillowOutputStream(threshold, outputFile,
listeners, isFormField());

      if(this.listeners != null && !isFormField()) {
        for(int i = 0; i < listeners.size(); i++) {
          UploadListener uploadlistener =
(UploadListener)listeners.elementAt(i);
          uploadlistener.fileUploadStarted(outputFile, totalSize,
getContentType());
        }

      }
    }
    return this.cwos;
  }


  public long getSize() {
    if(data != null) {
      return (long)data.length;
    }

    if(this.cwos.isInMemory()) {
      return (long)cwos.getData().length;
    } else {
      return cwos.getFile().length();
    }
  }

  public File getStoreLocation() {
    return cwos.getFile();
  }

  public String getString(String encoding)
      throws UnsupportedEncodingException {
    return new String(get(), encoding);
  }

  public String getString() {
    return new String(get());
  }

  public File getTempFile() {
    File file = tempDir;

    if(file == null) {
      file = new File(System.getProperty("java.io.tmpdir"));
    }

    String fileName = UploadConstant.FILE_PREFIX + getTempDirNumber() + ".tmp";
    File   tempFile = new File(file, fileName);

    tempFile.deleteOnExit();
    return tempFile;
  }

  private static String getTempDirNumber() {
    int i;
    synchronized(com.crackwillow.app.load.upload.crackwillow.CrackWillowFileItem.class)
{
      i = tempFileNumber++;
    }
    String fileNameNumber = Integer.toString(i);
    if(i < 0x5f5e100)
      fileNameNumber = ("00000000" +
fileNameNumber).substring(fileNameNumber.length());
    return fileNameNumber;
  }

  public boolean isFormField() {
    return isFormField;
  }

  public boolean isInMemory() {
    return cwos.isInMemory();
  }

  public void setFieldName(String fieldName) {
    this.fieldName = fieldName;
  }

  public void setFormField(boolean isFormField) {
    this.isFormField = isFormField;
  }

  public void write(File file)
      throws Exception {
    if(isInMemory()) {
      FileOutputStream fos = null;
      try {
        fos = new FileOutputStream(file);
        fos.write(get());
      } finally {
        if(fos != null) {
          fos.close();
        }
      }
    } else {
      File storeFile = getStoreLocation();
      if(storeFile != null) {
        if(!storeFile.renameTo(file)) {
          BufferedInputStream bis = null;
          BufferedOutputStream bos = null;
          try {
            bis = new BufferedInputStream(new FileInputStream(storeFile));
            bos = new BufferedOutputStream(new FileOutputStream(file));
            byte data0[] = new byte[2048];
            for(int i = 0; (i = bis.read(data0)) != -1;)
              bos.write(data0, 0, i);
          } finally {
            try {
              bis.close();
            } catch(IOException ioe) { }
            try {
              bos.close();
            } catch(IOException ioe1) { }
          }
        }
      } else {
        throw new IOException("Cannot write file to disk!");
      }
    }
  }

}



public class CrackWillowMultipart {

  public CrackWillowMultipart() {
  }

  public void handleRequest(HttpServletRequest req,
                            Vector             listeners,
                            int                maxFileSize,
                            Hashtable          parameterNames,
                            Hashtable          files,
                            String             repositoryPath,
                            String             encoding)
      throws IOException {

    CrackWillowFileItemFactory cffiFactory = new CrackWillowFileItemFactory();

    cffiFactory.setListeners(listeners);
    cffiFactory.setCustom(req.getContentLength());

    CommonsDiskFileUpload cdfu = new CommonsDiskFileUpload();

    cdfu.setFileItemFactory(cffiFactory);
    cdfu.setSizeMax(maxFileSize);
    cdfu.setSizeThreshold(UploadConstant.BUFFER_SIZE);
    cdfu.setRepositoryPath(repositoryPath);

    if(encoding != null) {
      cdfu.setHeaderEncoding(encoding);
    }

    List list = null;

    try {
      list = cdfu.parseRequest(req);
    } catch(CommonsFileUploadException fileuploade) {
      throw new IOException(fileuploade.getMessage());
    }

    Object obj = null;

    for(Iterator iterator = list.iterator(); iterator.hasNext();) {

      CommonsFileItem cfi       = (CommonsFileItem)iterator.next();
      String          fieldName = cfi.getFieldName();

      if(cfi.isFormField()) {
        String s3 = null;
        if(encoding != null) {
          s3 = cfi.getString(encoding);
        } else {
          s3 = cfi.getString();
        }

        Vector vector = (Vector)parameterNames.get(fieldName);

        if(vector == null) {
          vector = new Vector();
          parameterNames.put(fieldName, vector);
        }

        vector.addElement(s3);
      } else {
        String name = cfi.getName();
        if(name != null) {
          CrackWillowUploadFile fuuf = new CrackWillowUploadFile(cfi);
          name = name.replace('\\', '/');
          int j = name.lastIndexOf("/");

          if(j != -1) {
            name = name.substring(j + 1, name.length());
          }

          fuuf.setFileName(name);
          fuuf.setContentType(cfi.getContentType());
          fuuf.setFileSize(cfi.getSize());
          files.put(fieldName, fuuf);
        }
      }
    }

  }
}

You get the idea.  The main thing is that commons upload is pretty
much usable out of the box and you can decorate the classes as you see
fit to use as you like.

Jack

---------------------------------------------------------------------
To unsubscribe, e-mail: commons-user-unsubscribe@jakarta.apache.org
For additional commands, e-mail: commons-user-help@jakarta.apache.org


Mime
View raw message