1 5 package com.oreilly.servlet.multipart; 6 7 import java.io.File ; 8 import java.io.InputStream ; 9 import java.io.OutputStream ; 10 import java.io.BufferedOutputStream ; 11 import java.io.FileOutputStream ; 12 import java.io.IOException ; 13 import javax.servlet.ServletInputStream ; 14 15 28 public class FilePart extends Part { 29 30 31 private String fileName; 32 33 34 private String filePath; 35 36 37 private String contentType; 38 39 40 private PartInputStream partInput; 41 42 43 private FileRenamePolicy policy; 44 45 60 FilePart(String name, ServletInputStream in, String boundary, 61 String contentType, String fileName, String filePath) 62 throws IOException { 63 super(name); 64 this.fileName = fileName; 65 this.filePath = filePath; 66 this.contentType = contentType; 67 partInput = new PartInputStream(in, boundary); 68 } 69 70 73 public void setRenamePolicy(FileRenamePolicy policy) { 74 this.policy = policy; 75 } 76 77 91 public String getFileName() { 92 return fileName; 93 } 94 95 105 public String getFilePath() { 106 return filePath; 107 } 108 109 114 public String getContentType() { 115 return contentType; 116 } 117 118 129 public InputStream getInputStream() { 130 return partInput; 131 } 132 133 143 public long writeTo(File fileOrDirectory) throws IOException { 144 long written = 0; 145 146 OutputStream fileOut = null; 147 try { 148 if (fileName != null) { 150 File file; 152 if (fileOrDirectory.isDirectory()) { 153 file = new File (fileOrDirectory, fileName); 156 } 157 else { 158 file = fileOrDirectory; 161 } 162 if (policy != null) { 163 file = policy.rename(file); 164 fileName = file.getName(); 165 } 166 fileOut = new BufferedOutputStream (new FileOutputStream (file)); 167 written = write(fileOut); 168 } 169 } 170 finally { 171 if (fileOut != null) fileOut.close(); 172 } 173 return written; 174 } 175 176 183 public long writeTo(OutputStream out) throws IOException { 184 long size=0; 185 if (fileName != null) { 187 size = write( out ); 189 } 190 return size; 191 } 192 193 200 long write(OutputStream out) throws IOException { 201 if (contentType.equals("application/x-macbinary")) { 203 out = new MacBinaryDecoderOutputStream(out); 204 } 205 long size=0; 206 int read; 207 byte[] buf = new byte[8 * 1024]; 208 while((read = partInput.read(buf)) != -1) { 209 out.write(buf, 0, read); 210 size += read; 211 } 212 return size; 213 } 214 215 220 public boolean isFile() { 221 return true; 222 } 223 } 224 | Popular Tags |