如何在JSF中保存上传的文件我正在JSF中上传一个文件。我用的是战斧<t:inputFileUpload>对于这一点,但同样的问题适用于例如PrimeFaces<p:fileUpload>和JSF 2.2<h:inputFile>.我有以下支持bean代码:private UploadedFile uploadedFile; // +getter+setterpublic String save() throws IOException {
String name = uploadedFile.getName();
System.out.println("File name: " + name);
String type = uploadedFile.getContentType();
System.out.println("File type: " + type);
long size = uploadedFile.getSize();
System.out.println("File size: " + size);
InputStream stream = uploadedFile.getInputStream();
byte[] buffer = new byte[(int) size];
stream.read(buffer, 0, (int) size);
stream.close(); }我能够获得文件名、类型和大小,但无法将该文件保存在特定路径上。我想不出保存上传文件的正确方法。我怎样才能做到这一点?
3 回答
HUX布斯
TA贡献1876条经验 获得超6个赞
getInputStream()
InputStream input = uploadedFile.getInputStream();
/path/to/uploads
getRealPath()
Files#createTempFile()
Path folder = Paths.get("/path/to/uploads");String filename = FilenameUtils.getBaseName(uploadedFile.getName()); String extension = FilenameUtils.getExtension(uploadedFile.getName()); Path file = Files.createTempFile(folder, filename + "-", "." + extension);
FilenameUtils
try (InputStream input = uploadedFile.getInputStream()) { Files.copy(input, file, StandardCopyOption.REPLACE_EXISTING);}System.out.println("Uploaded file successfully saved in " + file);
/path/to/uploads
添加回答
举报
0/150
提交
取消