-
FEATURED COMPONENTS
First time here? Check out the FAQ!
Upload file to the server,here is the partial codes.
......
String sysPath = Executions.getCurrent().getDesktop().getWebApp().getRealPath("");
File file = new File(sysPath +"something...");
FileOutputStream out = null;
InputStream is = null;
byte[] buffer = new byte[1024];
int pointer = 0;
try {
out = new FileOutputStream(file);
is = amedia.getStreamData(); // Does not support ".txt"
while((pointer = is.read(buffer))!= -1){
out.write(buffer, 0, pointer);
}
} catch (IOException e) {
......
}
You have to take care of binary and in-memory data when handling media-objects. I'm using a simple helper-class which takes care of the different types of upload. You can simply call Medias.asFile(yourMedia) and retrieve a java.io.File with the content. If you don't want to use it directly, it should give you the idea how to handle the different cases.
HTH, Maik
import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; import java.io.OutputStream; import java.io.Reader; import java.io.StringReader; import org.apache.commons.io.IOUtils; import org.zkoss.util.media.Media; public class Medias { public static InputStream asStream(Media media) { return new BufferedInputStream( media.inMemory() ? new ByteArrayInputStream(media.getByteData()) : media.getStreamData()); } public static Reader asReader(Media media) { return new BufferedReader(media.inMemory() ? new StringReader(media .getStringData()) : media.getReaderData()); } public static File asFile(Media media) { try { File directory = createTempDirectory(); File file = new File(directory.getPath() + File.separator + media.getName()); OutputStream output = new FileOutputStream(file); if (media.isBinary()) { InputStream input = Medias.asStream(media); IOUtils.copy(input, output); input.close(); } else { Reader input = Medias.asReader(media); IOUtils.copy(input, output); input.close(); } output.close(); return file; } catch (Exception e) { throw new RuntimeException(e); } } public static String asString(Media media) { try { String result = null; if (media.isBinary()) { InputStream input = Medias.asStream(media); result = IOUtils.toString(input); input.close(); } else { Reader reader = Medias.asReader(media); result = IOUtils.toString(reader); reader.close(); } return result; } catch (Exception e) { throw new RuntimeException(e); } } private static File createTempDirectory() { try { File directory = File.createTempFile("jfix-util-", ""); directory.delete(); directory.mkdirs(); return directory; } catch (java.io.IOException e) { throw new RuntimeException(e); } } }
Asked: 2010-08-25 05:17:25 +0800
Seen: 497 times
Last updated: Aug 25 '10