You are viewing a plain text version of this content. The canonical link for it is here.
Posted to user@commons.apache.org by jackie <ja...@a2suite.com> on 2004/12/21 06:02:00 UTC

uploading image?

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.

I tried a lot of things but I am not sure how,  I search about commons file 
upload plugin and I think it is very reasonable to use.

I tried using with struts with "Form File " but I only upload and displays 
text files.

Now I am implementing commons-file upload in struts environment, Can anyone 
give me a hand?

Thank`s

Cheers,
yuubouna



Re: uploading image?

Posted by Dakota Jack <da...@gmail.com>.
On Tue, 21 Dec 2004 14:02:00 +0900, jackie <ja...@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


Re: uploading image?

Posted by Martin Cooper <mf...@gmail.com>.
On Tue, 21 Dec 2004 11:27:53 -0800, Dakota Jack <da...@gmail.com> wrote:
> Yuubouna and Martin,
> 
> I apologize for not knowing whether your name (Yuubouna) is male or
> female.  No disrespect intended.
> 
> 
> On Tue, 21 Dec 2004 08:50:10 -0800, Martin Cooper <mf...@gmail.com> wrote:
> > Struts actually uses Commons FileUpload for its upload functionality,
> > and you'll be able to do what you need with Struts itself. The Struts
> > FormFile interface handles both text and binary uploads. All you need
> > to do is decide where you want to store the image on disk.
> 
> I think s/he looked at this, Martin, and expressed a desire to build
> her/his own implementation of commons-upload and expressly rejected
> the Struts implementation.

What I read in the original message was a comment that the Struts file
upload implementation works only for text files, which is why yuubouna
turned to Commons FileUpload. Since it is not true that the Struts
implementation works only for text files, I suggested looking at it
further and taking the question up on the Struts User list, where
hundreds, if not thousands, of people have successfully used the
Struts implementation to upload binary files.

--
Martin Cooper


> I did the same thing.
> 
> Anyway, following Ted warning to trust committers and to do what
> committers say, Yuubouna, any further discussion I have with you about
> commons-upload apparently will have to be on struts-user list unless
> Martin changes his mind.  I am interested in these discussions and not
> the least bit interested in the Struts implementation myself.
> 
> Jack
> 
> --
> "You can lead a horse to water but you cannot make it float on its back."
> 
> ~Dakota Jack~
> 
> "You can't wake a person who is pretending to be asleep."
> 
> ~Native Proverb~
> 
> "Each man is good in His sight. It is not necessary for eagles to be crows."
> 
> ~Hunkesni (Sitting Bull), Hunkpapa Sioux~
> 
> -----------------------------------------------
> 
> "This message may contain confidential and/or privileged information.
> If you are not the addressee or authorized to receive this for the
> addressee, you must not use, copy, disclose, or take any action based
> on this message or any information herein. If you have received this
> message in error, please advise the sender immediately by reply e-mail
> and delete this message. Thank you for your cooperation."
>

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


Re: uploading image?

Posted by Dakota Jack <da...@gmail.com>.
Yuubouna and Martin,

I apologize for not knowing whether your name (Yuubouna) is male or
female.  No disrespect intended.


On Tue, 21 Dec 2004 08:50:10 -0800, Martin Cooper <mf...@gmail.com> wrote:
> Struts actually uses Commons FileUpload for its upload functionality,
> and you'll be able to do what you need with Struts itself. The Struts
> FormFile interface handles both text and binary uploads. All you need
> to do is decide where you want to store the image on disk.

I think s/he looked at this, Martin, and expressed a desire to build
her/his own implementation of commons-upload and expressly rejected
the Struts implementation.

I did the same thing.

Anyway, following Ted warning to trust committers and to do what
committers say, Yuubouna, any further discussion I have with you about
commons-upload apparently will have to be on struts-user list unless
Martin changes his mind.  I am interested in these discussions and not
the least bit interested in the Struts implementation myself.

Jack


-- 
"You can lead a horse to water but you cannot make it float on its back."

~Dakota Jack~

"You can't wake a person who is pretending to be asleep."

~Native Proverb~

"Each man is good in His sight. It is not necessary for eagles to be crows."

~Hunkesni (Sitting Bull), Hunkpapa Sioux~

-----------------------------------------------

"This message may contain confidential and/or privileged information.
If you are not the addressee or authorized to receive this for the
addressee, you must not use, copy, disclose, or take any action based
on this message or any information herein. If you have received this
message in error, please advise the sender immediately by reply e-mail
and delete this message. Thank you for your cooperation."

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


Re: uploading image?

Posted by Martin Cooper <mf...@gmail.com>.
Struts actually uses Commons FileUpload for its upload functionality,
and you'll be able to do what you need with Struts itself. The Struts
FormFile interface handles both text and binary uploads. All you need
to do is decide where you want to store the image on disk.

Displaying the image on the page is independent of the upload process.
Depending on where you stored the uploaded image, you may be able to
use an app-relative URL to retrieve it. Otherwise, you may need to
serve it up using a servlet.

If you have more questions on this, I recommend that you ask them on
the Struts User list. There are many people on that list who have done
exactly what you are trying to accomplish with Struts.

--
Martin Cooper


On Tue, 21 Dec 2004 14:02:00 +0900, jackie <ja...@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.
> 
> I tried a lot of things but I am not sure how,  I search about commons file
> upload plugin and I think it is very reasonable to use.
> 
> I tried using with struts with "Form File " but I only upload and displays
> text files.
> 
> Now I am implementing commons-file upload in struts environment, Can anyone
> give me a hand?
> 
> Thank`s
> 
> Cheers,
> yuubouna
> 
>

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