Código JSP:
<html:form action="/snapshotUploadAction.do" method="post" enctype="multipart/form-data">
File : <html:file property="formFile" /> <html:submit />
</html:form>
<c:if test="${not empty fileUploadForm.message}">
<p style="color:red;">${fileUploadForm.message}</p>
</c:if>
Código del ActionForm:
import org.apache.struts.action.ActionForm;
import org.apache.struts.upload.FormFile;
public class FileUploadForm extends ActionForm {
private static final long serialVersionUID = 1L;
protected FormFile formFile;
protected String message;
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public FormFile getFormFile() {
return formFile;
}
public void setFormFile(FormFile formFile) {
this.formFile = formFile;
}
}
Código del Action:
import java.io.File;
import java.io.FileOutputStream;
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;
import com.eol.core.controller.form.FileUploadForm;
/**
* Basic action to be used to upload files.
* @author gsolano
*
*/
public class FileUploadAction extends Action{
@Override
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
FileUploadForm uploadForm = (FileUploadForm) form;
FileOutputStream outputStream = null;
FormFile formFile = null;
String path="";
formFile = uploadForm.getFormFile();
if(formFile != null) {
try {
path = getRepositoryPath() + formFile.getFileName();
System.out.println("File will be uploaded to this path: " + path);
outputStream = new FileOutputStream(new File(path));
outputStream.write(formFile.getFileData());
} catch(Exception exception) {
System.out.println(exception);
}
finally {
if (outputStream != null) {
outputStream.close();
}
}
/* Do something with the just uploaded file*/
processUploadedFile(path);
uploadForm.setMessage("The file " + formFile.getFileName() + " was uploaded successfully.");
}
return mapping.findForward("success");
}
/**
*
* @param path
*/
protected void processUploadedFile(String path) {
/*MUST OVERRIDE TO DO SOMETHING WITH THE UPLOADED FILE*/
}
/**
* This path where the file will be uploaded is put in a method to allow
* classes extending to be able to override it.
* @return
*/
protected String getRepositoryPath() {
return getServlet().getServletContext().getRealPath("")+"/";
}
}
Resultado: