<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>AEXT.NET MAGAZINE &#187; Upload</title>
	<atom:link href="http://aext.net/tag/upload/feed/" rel="self" type="application/rss+xml" />
	<link>http://aext.net</link>
	<description>How to Create a Website</description>
	<lastBuildDate>Wed, 30 May 2012 05:03:57 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.2</generator>
		<item>
		<title>Struts: Upload file using Struts and Generates unique ID for file name</title>
		<link>http://aext.net/2008/06/struts-upload-file-using-struts-and-generates-unique-id-for-file-name/</link>
		<comments>http://aext.net/2008/06/struts-upload-file-using-struts-and-generates-unique-id-for-file-name/#comments</comments>
		<pubDate>Sat, 28 Jun 2008 11:36:00 +0000</pubDate>
		<dc:creator>Lief</dc:creator>
				<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Struts]]></category>
		<category><![CDATA[Upload]]></category>

		<guid isPermaLink="false">http://lamnguyenblog.com/2008/06/struts-upload-file-using-struts-and-generates-unique-id-for-file-name/</guid>
		<description><![CDATA[<p><a href="http://aext.net/theme/platinoom" title="Platinoom - Premium WordPress Themes"><img src="http://aext.net/wp-content/uploads/2011/04/platinoom_wordpress_theme.png" alt="ThemeKiss" /></a></p><p style="float: right;"><a href="http://api.tweetmeme.com/share?url=http://aext.net/2008/06/struts-upload-file-using-struts-and-generates-unique-id-for-file-name/&service=su.pr&service_api=b57727e991c454bd2b2c62ff71462c79"><img src="http://api.tweetmeme.com/imagebutton.gif?url=http://aext.net/2008/06/struts-upload-file-using-struts-and-generates-unique-id-for-file-name/" height="61" width="51" /></a></p>]]></description>
			<content:encoded><![CDATA[<p><a href="http://aext.net/theme/platinoom" title="Platinoom - Premium WordPress Themes"><img src="http://aext.net/wp-content/uploads/2011/04/platinoom_wordpress_theme.png" alt="ThemeKiss" /></a></p><p style="float: right;"><a href="http://api.tweetmeme.com/share?url=http://aext.net/2008/06/struts-upload-file-using-struts-and-generates-unique-id-for-file-name/&service=su.pr&service_api=b57727e991c454bd2b2c62ff71462c79"><img src="http://api.tweetmeme.com/imagebutton.gif?url=http://aext.net/2008/06/struts-upload-file-using-struts-and-generates-unique-id-for-file-name/" height="61" width="51" /></a></p><p>Someone finding the way to upload file with struts, it&#8217;s simple&#8230;You only create form with Struts: Form class with file property is FormFile. But,..how to upload file to server with unique name in folder if some file has same name ???. Now, with this post, you&#8217;ll resolve it, very simple!!!.</p>
<p>First, simply create your Struts form class, below is <span style="font-weight: bold;">UploadFileForm</span>, class extends ValidatorActionForm because i want to validate Form for uploading, class:</p>
<pre class="java" name="code">package prlamnguyen.struts.form;

import javax.servlet.http.HttpServletRequest;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.upload.FormFile;
import org.apache.struts.validator.ValidatorActionForm;

/**
* Upload File Form Class.
*
* <span style="font-weight: bold;">@author</span> prlamnguyen
* <span style="font-weight: bold;">@link</span> http://prlamnguyen.blogspot.com/2008/06/upload-file-using-struts-and-generates.html
*/

public class UploadFileForm extends ValidatorActionForm {

   /*
   * Extends ValidatorActionForm if you want to validate form
   */

   /** image property */
   private String fileName;

   /** fileImage property */
   private FormFile file

   /**
   * @return the file
   */
   public FormFile getFile() {
      return file;
   }

   /**
   * @return the fileName
   */
   public String getFileName() {
      return fileName;
   }

   /**
   * @param file the file to set
   */
   public void setFileImage(FormFile file){
      this.file = file;
   }

   /**
   * @param fileName the fileName to set
   */
   public void setImage(String fileName) {
      this.fileName = fileName;
   }

   /**
   * Method validate
   * @param mapping
   * @param request
   * @return ActionErrors
   */
   public ActionErrors validate(ActionMapping mapping,
   HttpServletRequest request) {
      // Validate your form if you want
      // This helpful for validate type of file, size, extension of file ....
      return null;
   }

   /**
   * Method reset
   * @param mapping
   * @param request
   */
   public void reset(ActionMapping mapping, HttpServletRequest request) {
      // Reset your form input
   }

}
</pre>
<p><span id="fullpost"></p>
<p>
Above is UploadFileForm class, we have 2 properties: (String) fileName and (FormFile)file , with property file, you must import org.apache.struts.upload.FormFile which is struts capabilities, with MyEclipse 3.x or above, you can do that simply.</p>
<p>Now, we must create action class for struts, name of action class is UploadFileAction:</p>
<p>
</span></p>
<pre class="java" name="code">package prlamnguyen.struts.action;

import java.io.File;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import prlamnguyen.struts.form.UploadFileForm;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.upload.FormFile;

/**
* Creation date: 05-31-2008
*
* Upload File Action Class.
*
* <b>@author</b> prlamnguyen
* <b>@link</b> http://prlamnguyen.blogspot.com/2008/06/upload-file-using-struts-and-generates.html
*
* Definition:
* <b>@struts</b>.action path="/uploadFile" name="uploadFileForm" input="/upload_file.jsp" scope="request" validate="true"
* <b>@struts</b>.action-forward name="failed" path="/upload_file.jsp"
* <b>@struts</b>.action-forward name="success" path="/upload_successful.jsp"
*/
public class UploadFileAction extends Action {
   /*
   * Generated Methods
   */

   /**
&nbsp;&nbsp;&nbsp;*
&nbsp;&nbsp;&nbsp;* <b>@param</b> uploadForm
&nbsp;&nbsp;&nbsp;* <b>@return</b>
&nbsp;&nbsp;&nbsp;*/
   public String uploadFile(UploadFileForm uploadForm) {
      // Process the FormFile
      FormFile myFile = uploadForm.getFile();
      String fileName="default";
      // Get the file name
      try {
          // Precreate an unique file and then write the InputStream of the uploaded file to it.
          File uniqueFile = DoFile.uniqueFile(new File("your file patch"), myFile.getFileName());
          DoFile.write(uniqueFile, myFile.getInputStream());
          fileName = uniqueFile.getName();

          // Show succes message.
          System.out.println("Upload file complete");

      } catch (IOException e) {

          // Show error message.
          System.out.println("Upload file failed");

          // Always log stacktraces.
          e.printStackTrace();
      }
      return fileName;
   }

   /**
&nbsp;&nbsp;&nbsp;* Method execute
&nbsp;&nbsp;&nbsp;* <b>@param</b> mapping
&nbsp;&nbsp;&nbsp;* <b>@param</b> form
&nbsp;&nbsp;&nbsp;* <b>@param</b> request
&nbsp;&nbsp;&nbsp;* <b>@param</b> response
&nbsp;&nbsp;&nbsp;* <b>@return</b> ActionForward
&nbsp;&nbsp;&nbsp;*/
   public ActionForward execute(ActionMapping mapping, ActionForm form,
       HttpServletRequest request, HttpServletResponse response) {
       UploadFileForm uploadForm = (UploadFileForm) form;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;// to do execute
       ActionForward forward = new ActionForward();

       image = uploadImage(uploadForm);

       return forward = mapping.findForward("success");
   }
}
</pre>
<p><span id="fullpost"></p>
<p>Ukie, all important thing done, DoFile above is one class file you must declare, and Struts must be config-ed:</p>
<p></span></p>
<ul><span id="fullpost"></p>
<li><b>DoFile Class:</b></li>
<p></span></ul>
<p></p>
<pre class="java" name="code">/**
* Generate unique file based on the given path and name. If the file exists, then it will
* add "[i]" to the file name as long as the file exists. The value of i can be between
* 0 and 2147483647 (the value of Integer.MAX_VALUE).
* <b>@param</b> filePath The path of the unique file.
* <b>@param</b> fileName The name of the unique file.
* <b>@return</b> The unique file.
* <b>@throws</b> IOException If unique file cannot be generated, this can be caused if all file
* names are already in use. You may consider another filename instead.
*/
public static File uniqueFile(File filePath, String fileName) throws IOException {
   File file = new File(filePath, fileName);
   if (file.exists()) {
   &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;// Split filename and add braces, e.g. "name.ext" --&gt; "name[", "].ext".

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;String prefix;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;String suffix;
      &nbsp;&nbsp;int dotIndex = fileName.lastIndexOf(".");

    &nbsp;&nbsp;&nbsp;if (dotIndex &gt; -1) {
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;prefix = fileName.substring(0, dotIndex) + "[";
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;suffix = "]" + fileName.substring(dotIndex);
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;} else {
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;prefix = fileName + "[";
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;suffix = "]";
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;int count = 0;
      &nbsp;&nbsp;// Add counter to filename as long as file exists.

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;while (file.exists()) {

       &nbsp;&nbsp;&nbsp;if (count &lt; 0) { // int++ restarts at -2147483648 after 2147483647.
          &nbsp;&nbsp;&nbsp;throw new IOException("No unique filename available for " + fileName
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;+ " in path " + filePath.getPath() + ".");
       &nbsp;&nbsp;&nbsp;&nbsp;}
       &nbsp;&nbsp;&nbsp;&nbsp;// Glue counter between prefix and suffix, e.g. "name[" + count + "].ext".
       &nbsp;&nbsp;&nbsp;&nbsp;file = new File(filePath, prefix + (count++) + suffix);

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}
   }

   return file;
}

/**
* Write byte inputstream to file. If file already exists, it will be overwritten.It's highly
* recommended to feed the inputstream as BufferedInputStream or ByteArrayInputStream as those
* are been automatically buffered.
* <b>@param</b> file The file where the given byte inputstream have to be written to.
* <b>@param</b> input The byte inputstream which have to be written to the given file.
* <b>@throws</b> IOException If writing file fails.
*/
public static void write(File file, InputStream input) throws IOException {
   write(file, input, false);
}
</pre>
<p><span id="fullpost"></p>
<p></span></p>
<ul><span id="fullpost"></p>
<li class="comment-footer"><b>Struts Config:</b></li>
<p></span></ul>
<p><span id="fullpost"><br />
</span></p>
<pre class="xml" name="code">&lt;form-beans &gt;
  &lt;form-bean name="UploadFileForm" type="prlamnguyen.struts.form.UploadFileForm" /&gt;
&lt;/form-beans&gt;

&lt;action-mappings &gt;
&lt;action
attribute="uploadForm"
    input="/upload_file.jsp"
    name="uploadFileForm"
    path="/uploadFile"
    scope="request"
    type="prlamnguyen.struts.action.UploadFileAction"&gt;
    &lt;forward name="failed" path="/upload_file.jsp" /&gt;
    &lt;forward name="success" path="/upload_successful.jsp" /&gt;
&lt;/action&gt;
&lt;/action-mappings&gt;
</pre>
<p><span id="fullpost"></p>
<p>Done, finish is create new JSP page and create Struts Form JSP, to upload your file, form with property:  <span style="font-weight: bold;">file</span>.</p>
<p>Now, use any edit program, create new jsp file, here i create <span style="font-weight: bold;">upload_file.jsp</span> (for input and forward failed)  :<br />
</span></p>
<pre class="html" name="code">&lt;html:form action="/uploadFile" enctype="multipart/form-data"&gt;
&lt;table width="100%" border="0" cellspacing="0" cellpadding="0"&gt;
&nbsp;&lt;tr&gt;
&nbsp;&nbsp;&nbsp;&lt;td class="spectd"&gt;Chose file to upload: &lt;/td&gt;
&nbsp;&nbsp;&nbsp;&lt;td&gt;&lt;html:file property="file"/&gt; &lt;html:errors property="file"/&gt;&lt;/td&gt;
&nbsp;&lt;/tr&gt;
&lt;/table&gt;
&lt;div align="center"&gt;
&nbsp;&lt;html:submit/&gt;&amp;nbsp;&amp;nbsp;&lt;html:reset/&gt;
&lt;/div&gt;
&lt;/html:form&gt;
</pre>
<p><span id="fullpost"><br />
Note: you must have enctype=&#8221;multipart/form-data&#8221; to  send request upload file to server.</p>
<p>You should create successful page to print out when upload successful. In struts config, i created config-forward &#8220;success&#8221; with <b>upload_successful.jsp</b> jsp page.</p>
<p>If you done everything above, all classes were created, build all and deploy into your server and testing from url: <a href="http://localhost:8080/UploadFile/upload_file.jsp">http://localhost:8080/UploadFile/upload_file.jsp</a>.</p>
<p>All wrong please email <a href="mailto:prlam.nguyen@gmail.com">prlam.nguyen@gmail.com</a> or comment here.<br />
Regard!  </p>
<p></span></p>
<div class="article-copyright"><span id="fullpost">Â© 2008, Lam Duy Nguyen</span></div>
<div class="blogger-post-footer">Nguyen, Lam D&#8217;s Bloger &#8211; http://prlamnguyen.blogspot.com</div>
]]></content:encoded>
			<wfw:commentRss>http://aext.net/2008/06/struts-upload-file-using-struts-and-generates-unique-id-for-file-name/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
	</channel>
</rss>

