File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Struts and the fly likes Upload file using Struts Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Frameworks » Struts
Bookmark "Upload file using Struts" Watch "Upload file using Struts" New topic
Author

Upload file using Struts

Sherryl Philip
Greenhorn

Joined: Jul 02, 2004
Posts: 20
Hi,
I need to upload a file on to my tomcat server. Actually the client will need to upload a particular file to my tomcat server. How can this be done? Could anyone please help me as I'm completely unaware of how to do this? If you could provide a sample code i would be happy.

Thanks a lot in advance.
Sherryl
Tom George
Ranch Hand

Joined: Jan 28, 2004
Posts: 41
The file content is to be passed in the request body using POST, setting the mime type as 'multipart/form-data'. More documentation and links available at http://www.jguru.com/faq/view.jsp?EID=160

As noted there,
"Please note that you can't access a file on the client system directly from a servlet; that would be a huge security hole. You have to ask the user for permission, and currently form-based upload is the only way to do that."

A lot of pre-built classes are available for this.
Ali Gohar
Ranch Hand

Joined: Mar 18, 2004
Posts: 572
Hi,
There is book available online for free "JakartaStrutsLive" at www.theserverside.com. In this book the method of file upload in Struts is explained. Its very simple.You can take the help from this book.

There are a lot of APIs available on internet for the file upload if you are not using Struts. You can search through google.
Bear Bibeault
Author and ninkuma
Marshal

Joined: Jan 10, 2002
Posts: 60780
    
  65

Moving to the Frameworks forum.


[Asking smart questions] [Bear's FrontMan] [About Bear] [Books by Bear]
Sherryl Philip
Greenhorn

Joined: Jul 02, 2004
Posts: 20
Hi
Thanks Ali and Tom.
Listen, I'd like to work with struts. I've tried out with the follwing code. But the filepath is not being read by itself. Could you please tell how can I tackle this in a better way.

UploadAction.java

package com.bang.upload;

import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

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;


/**
* This class takes the UploadForm and retrieves the text value
* and file attributes and puts them in the request for the display.jsp
* page to display them
*
* @author
* @version $Revision: 1.8 $ $Date: 2004/07/03 $
*/


public class UploadAction extends Action
{
public ActionForward execute(ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response)
throws Exception {

if (form instanceof UploadForm) {

//this line is here for when the input page is upload-utf8.jsp,
//it sets the correct character encoding for the response
String encoding = request.getCharacterEncoding();

if ((encoding != null) && (encoding.equalsIgnoreCase("utf-8")))
{
response.setContentType("text/html; charset=utf-8");
}

UploadForm theForm = (UploadForm) form;

//retrieve the text data
String text = theForm.getTheText();

//retrieve the query string value
String queryValue = theForm.getQueryParam();

//retrieve the file representation
FormFile file = theForm.getTheFile();
System.out.println("file :"+ file);

//retrieve the file name
String fileName= file.getFileName();
System.out.println("file Name"+fileName);

//retrieve the content type
String contentType = file.getContentType();

boolean writeFile = theForm.getWriteFile();

System.out.println("Write File"+writeFile);

//retrieve the file size
String size = (file.getFileSize() + " bytes");
System.out.println("Size:"+size);
String data = null;

try {
//retrieve the file data
ByteArrayOutputStream baos = new ByteArrayOutputStream();
InputStream stream = file.getInputStream();
if (!writeFile) {
//only write files out that are less than 1MB
if (file.getFileSize() < (4*1024000)) {

byte[] buffer = new byte[8192];
int bytesRead = 0;
while ((bytesRead = stream.read(buffer, 0, 8192)) != -1) {
baos.write(buffer, 0, bytesRead);
System.out.println("Buffer:" +buffer);
}
data = new String(baos.toByteArray());
System.out.println("Data:"+data);
}
else {
data = new String("The file is greater than 4MB, " +
" and has not been written to stream." +
" File Size: " + file.getFileSize() + " bytes. This is a" +
" limitation of this particular web application, hard-coded" +
" in org.apache.struts.webapp.upload.UploadAction");
}

}
else {
try{

//write the file to the file specified
System.out.println(theForm.getFilePath());
OutputStream bos = new FileOutputStream(theForm.getFilePath());
System.out.println(theForm.getFilePath());
int bytesRead = 0;
byte[] buffer = new byte[8192];
while ((bytesRead = stream.read(buffer, 0, 8192)) != -1) {
bos.write(buffer, 0, bytesRead);
}
bos.close();
data = "The file has been written to \"" + theForm.getFilePath() + "\"";
System.out.println("Data:"+data);
}catch(Exception e){
System.err.println(e.getMessage());
}
}
//close the stream
stream.close();
}
catch (FileNotFoundException fnfe) {
return null;
}
catch (IOException ioe) {
return null;
}

//place the data into the request for retrieval from display.jsp
request.setAttribute("text", text);
request.setAttribute("queryValue", queryValue);
request.setAttribute("fileName", fileName);
request.setAttribute("contentType", contentType);
request.setAttribute("size", size);
request.setAttribute("data", data);

//destroy the temporary file created
file.destroy();

//return a forward to display.jsp
return mapping.findForward("success");
}

//this shouldn't happen in this example
return null;
}
}


UploadForm.java

package com.bang.upload;

import org.apache.struts.upload.FormFile;
import org.apache.struts.action.ActionForm;


/**
* This class is a placeholder for form values. In a multipart request, files are represented by
* set and get methods that use the class org.apache.struts.upload.FormFile, an interface with
* basic methods to retrieve file information. The actual structure of the FormFile is dependant
* on the underlying impelementation of multipart request handling. The default implementation
* that struts uses is org.apache.struts.upload.DiskMultipartRequestHandler.
*
* @author
* @version $Revision: 1.3 $ $Date: 2004/07/03 12:54:09 $
*/

public class UploadForm extends ActionForm {

/**
* The value of the text the user has sent as form data
*/
protected String theText;

/**
* Whether or not to write to a file
*/
protected boolean writeFile;

/**
* The file that the user has uploaded
*/
protected FormFile theFile;

/**
* The file path to write to
*/
protected String filePath;
protected String queryParam;



/**
* Retrieve the value of the text the user has sent as form data
*/
public String getTheText() {
return theText;
}

/**
* Set the value of the form data text
*/
public void setTheText(String theText) {
this.theText = theText;
}

/**
* Retrieve a representation of the file the user has uploaded
*/
public FormFile getTheFile() {
return theFile;
}

/**
* Set a representation of the file the user has uploaded
*/
public void setTheFile(FormFile theFile) {
this.theFile = theFile;
}

/**
* Set whether or not to write to a file
*/
public void setWriteFile(boolean writeFile) {
this.writeFile = writeFile;
}

/**
* Get whether or not to write to a file
*/
public boolean getWriteFile() {
return writeFile;
}

/**
* Set the path to write a file to
*/
public void setQueryParam(String queryParam) {
this.queryParam = queryParam;
}

/**
* Get the path to write a file to
*/
public String getQueryParam() {
return queryParam;
}

public void setFilePath(String filePath) {
this.filePath = filePath;
}


public String getFilePath() {
return (filePath);
}


public void reset() {
writeFile = false;
}
}




upload.jsp

<%@ page contentType="text/html;charset=iso-8859-1" language="java" %>
<%@taglib uri="http://jakarta.apache.org/struts/tags-html" prefix="html"%>
<%@taglib uri="http://jakarta.apache.org/struts/tags-bean" prefix="bean"%>
<%@ taglib uri="http://jakarta.apache.org/struts/tags-tiles" prefix="tiles" %>
<html:html>
<html:form enctype="multipart/form-data" action="/upload" method="post" >

<h1>Add Article</h1>
Please enter file you wish to add:
<br><br>
<html:file property="theFile"/>
<br><br>
<html:submit value="Upload File" />
</html:form>

</html:html>

Thanks again in advance.

Regards
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Upload file using Struts
 
Similar Threads
JSP File upload
how to upload a file
wanted to impement file uploading
server path...
Upload Servlet