package org.appfuse.webapp.action;
import java.io.File;
import java.io.FileOutputStream;
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;
import org.appfuse.Constants;
import org.appfuse.webapp.form.UploadForm;
public class UploadAction extends Action {
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request,
HttpServletResponse response)
throws Exception {
if (isCancelled(request)) {
request.removeAttribute(mapping.getAttribute());
return (mapping.findForward("mainMenu"));
}
String encoding = request.getCharacterEncoding();
if ((encoding != null) && (encoding.equalsIgnoreCase("utf-8"))) {
response.setContentType("text/html; charset=utf-8");
}
UploadForm theForm = (UploadForm) form;
String name = theForm.getName();
FormFile file = theForm.getFile();
if (file == null) {
return mapping.findForward("failure");
}
String fileName = file.getFileName();
String contentType = file.getContentType();
String size = (file.getFileSize() + " bytes");
String data = null;
String filePath = null;
String uploadDir =
servlet.getServletContext().getRealPath("/resources") + "/"
+ request.getRemoteUser() + "/";
File dirPath = new File(uploadDir);
if (!dirPath.exists()) {
dirPath.mkdirs();
}
InputStream stream = file.getInputStream();
OutputStream bos = new FileOutputStream(uploadDir + fileName);
int bytesRead = 0;
byte[] buffer = new byte[8192];
while ((bytesRead = stream.read(buffer, 0, 8192)) != -1) {
bos.write(buffer, 0, bytesRead);
}
bos.close();
filePath = dirPath.getAbsolutePath() + Constants.FILE_SEP + file.getFileName();
stream.close();
request.setAttribute("friendlyName", name);
request.setAttribute("fileName", fileName);
request.setAttribute("contentType", contentType);
request.setAttribute("size", size);
request.setAttribute("data", data);
request.setAttribute("filePath", filePath);
String url = request.getContextPath() + "/resources" + "/" +
request.getRemoteUser() + "/" + file.getFileName();
request.setAttribute("url", url);
file.destroy();
return mapping.findForward("success");
}
}