We are receiving lots of comments regarding "Struts file upload example". It does not contain any code illustrating how to save the file on the server . Now, the current example will provide you with the code to upload the file ,in the upload directory of server.
In this tutorial you will learn how to use Struts program to upload on the Server and display a link to the user to download the uploaded file . The interface org.apache.struts.upload.FormFile has a prime role in uploading a file in a Struts application. This interface represents a file that has been uploaded by a client. It is the only interface or class in Upload package which is referenced directly by a Struts application.
Creating Form Bean
Our form bean class contains only one property theFile, which is of type org.apache.struts.upload.FormFile.
package roseindia.net;
|
Creating Action Class
In our previous article entitled "Struts File Upload Example", we just had action class simply calling the getTheFile() function on the FormBean object to retrieve the reference of the uploaded file. Then the reference of the FormFile was used to get the uploaded file and its information. Now further we retrieve the Servers upload directory's real path using ServletContext's getRealPath() and saving the file.
Code of StrutsUploadAndSaveAction.java:
package roseindia.net;
|
Defining form Bean in struts-config.xml file
Add the following entry in the struts-config.xml file for defining the form bean:
type="roseindia.net.StrutsUploadAndSaveForm"/> |
Add the following action mapping entry in the struts-config.xml file:
type="roseindia.net.StrutsUploadAndSaveAction" name="FileUploadAndSave" scope="request" validate="true" input="/pages/FileUploadAndSave.jsp"> |
Developing jsp pages
Code of the jsp (FileUploadAndSave.jsp) file to upload is as follows
<%@ taglib uri="/tags/struts-bean" prefix="bean" %>
<%@ taglib uri="/tags/struts-html" prefix="html" %>
|
code for the success page (downloaduploadedfile.jsp) is:
<% String fileName=(String)request.getAttribute("fileName"); %> File Successfully Received |
Add the following line in the index.jsp to call the form.
Example shows you how to Upload File with Struts.
Building Example and Testing
To build and deploy the application go to Struts\strutstutorial directory and type ant on the command prompt. This will deploy the application. Open the browser and navigate to the Struts File Upload page. Your browser should display the file upload form:
Now , Browse the file needed to upload and click Upload File Button. Browser will display that file has successfully received on the server.
0 comments:
Post a Comment