1 package org.appfuse.webapp.action; 2 3 import java.io.File ; 4 import java.io.FileOutputStream ; 5 import java.io.InputStream ; 6 import java.io.OutputStream ; 7 8 import javax.servlet.http.HttpServletRequest ; 9 import javax.servlet.http.HttpServletResponse ; 10 11 import org.apache.struts.action.Action; 12 import org.apache.struts.action.ActionForm; 13 import org.apache.struts.action.ActionForward; 14 import org.apache.struts.action.ActionMapping; 15 import org.apache.struts.upload.FormFile; 16 import org.appfuse.Constants; 17 import org.appfuse.webapp.form.UploadForm; 18 19 20 36 public class UploadAction extends Action { 37 public ActionForward execute(ActionMapping mapping, ActionForm form, 38 HttpServletRequest request, 39 HttpServletResponse response) 40 throws Exception { 41 if (isCancelled(request)) { 43 request.removeAttribute(mapping.getAttribute()); 44 return (mapping.findForward("mainMenu")); 45 } 46 47 String encoding = request.getCharacterEncoding(); 50 51 if ((encoding != null) && (encoding.equalsIgnoreCase("utf-8"))) { 52 response.setContentType("text/html; charset=utf-8"); 53 } 54 55 UploadForm theForm = (UploadForm) form; 56 57 String name = theForm.getName(); 59 60 FormFile file = theForm.getFile(); 62 63 if (file == null) { 64 return mapping.findForward("failure"); 65 } 66 67 String fileName = file.getFileName(); 69 70 String contentType = file.getContentType(); 72 73 String size = (file.getFileSize() + " bytes"); 75 76 String data = null; 77 String filePath = null; 78 79 String uploadDir = 81 servlet.getServletContext().getRealPath("/resources") + "/" 82 + request.getRemoteUser() + "/"; 83 84 File dirPath = new File (uploadDir); 86 87 if (!dirPath.exists()) { 88 dirPath.mkdirs(); 89 } 90 91 InputStream stream = file.getInputStream(); 93 94 OutputStream bos = new FileOutputStream (uploadDir + fileName); 96 int bytesRead = 0; 97 byte[] buffer = new byte[8192]; 98 99 while ((bytesRead = stream.read(buffer, 0, 8192)) != -1) { 100 bos.write(buffer, 0, bytesRead); 101 } 102 103 bos.close(); 104 105 filePath = dirPath.getAbsolutePath() + Constants.FILE_SEP + file.getFileName(); 106 107 stream.close(); 109 110 request.setAttribute("friendlyName", name); 112 request.setAttribute("fileName", fileName); 113 request.setAttribute("contentType", contentType); 114 request.setAttribute("size", size); 115 request.setAttribute("data", data); 116 request.setAttribute("filePath", filePath); 117 118 String url = request.getContextPath() + "/resources" + "/" + 119 request.getRemoteUser() + "/" + file.getFileName(); 120 request.setAttribute("url", url); 121 122 file.destroy(); 124 125 return mapping.findForward("success"); 127 } 128 } 129 | Popular Tags |