1 9 10 11 12 package org.apache.lenya.cms.authoring; 13 14 import org.apache.cocoon.environment.Request; 15 import org.apache.cocoon.servlet.multipart.Part; 16 import org.apache.log4j.Category; 17 18 import java.io.File ; 19 import java.io.FileOutputStream ; 20 import java.io.InputStream ; 21 import java.io.IOException ; 22 import java.io.OutputStream ; 23 24 30 public class UploadHelper { 31 32 private static final Category log = Category.getInstance(UploadHelper.class); 33 34 private File directory; 35 36 40 public UploadHelper(File directory) { 41 this.directory = directory; 42 } 43 44 48 public UploadHelper(String directoryPath) { 49 this.directory = new File (directoryPath); 50 } 51 52 57 public boolean save(Part part) { 58 File file = new File (directory, part.getFileName()); 59 return save(part, file); 60 } 61 62 67 public boolean save(Part part, File file) { 68 if (log.isDebugEnabled()) { 69 log.debug("Uploading file: [" + file.getAbsolutePath() + "]"); 70 } 71 72 if (!directory.isDirectory()) { 73 directory.mkdirs(); 74 if (log.isInfoEnabled()) { 75 log.info("Directory has been created: [" + directory + "]"); 76 } 77 } 78 79 InputStream in = null; 80 OutputStream out = null; 81 try { 82 out = new FileOutputStream (file.getAbsolutePath()); 83 in = part.getInputStream(); 84 byte[] buf = new byte[4096]; 85 int read = in.read(buf); 86 87 while (read > 0) { 88 out.write(buf, 0, read); 89 read = in.read(buf); 90 } 91 } catch (Exception e) { 92 log.error(e); 93 return false; 94 } finally { 95 try { 96 if (out != null) { 97 out.close(); 98 } 99 if (in != null) { 100 in.close(); 101 } 102 } catch (IOException e) { 103 log.error(e); 104 } 105 } 106 return true; 107 } 108 109 116 public File save(Request request, String requestParameter) throws Exception { 117 118 Part part = (Part) request.get(requestParameter); 119 120 File file = null; 121 122 boolean success = save(part); 123 if (success) { 124 file = new File (directory, part.getFileName()); 125 } 126 127 return file; 128 } 129 130 } 131 | Popular Tags |