[英]How to store uploaded mulitple pdf file to a specific location in java?
我想將上傳的文件存儲在Java中的特定位置。 如果我上傳a.pdf
那么我希望它將其存儲在"/home/rahul/doc/upload/"
。 我經歷了一些堆棧溢出的問題和答案,但對解決方案不滿意。
我正在使用Play Framework 2.1.2
。 我不使用servlet
。
我正在上傳,但它正在將文件存儲到temp目錄中,但我希望將該文件存儲到一個文件夾中而不是一個臨時文件中,我希望該文件像a.pdf一樣位於文件夾中,而不是像temp文件一樣。
public static Result upload() {
MultipartFormData body = request().body().asMultipartFormData();
FilePart filePart1 = body.getFile("filePart1");
File newFile1 = new File("path in computer");
File file1 = filePart1.getFile();
InputStream isFile1 = new FileInputStream(file1);
byte[] byteFile1 = IOUtils.toByteArray(isFile1);
FileUtils.writeByteArrayToFile(newFile1, byteFile1);
isFile1.close();
}
但我對這種解決方案不滿意,我正在上傳多個doc文件。
例如 我上傳了一個文檔ab.docx,然后上傳后存儲了temp目錄,文件是這樣的:
它的位置是這樣的: /tmp/multipartBody5886394566842144137asTemporaryFile
但我想要這個: /upload/ab.docx
告訴我一些解決方案。
一切都正確,這是您需要重renameTo
的最后一步。將臨時文件復制到您的上傳文件夾中,您無需在流中播放即可,它非常簡單:
public static Result upload() {
Http.MultipartFormData body = request().body().asMultipartFormData();
FilePart upload = body.getFile("picture");
if (upload != null) {
String targetPath = "/your/target/upload-dir/" + upload.getFilename();
upload.getFile().renameTo(new File(targetPath));
return ok("File saved in " + targetPath);
} else {
return badRequest("Something Wrong");
}
}
順便說一句,您應該實施一些檢查,以確定targetPath是否不存在以防止錯誤和/或覆蓋。 如果已經存在具有相同名稱的文件,則典型的方法是增加文件名,例如,發送3次a.pdf
的示例應將文件另存為a.pdf
, a_01.pdf
, a_02.pdf
等。
我剛完成。 我的解決方案工作正常。
我上傳多個文件的解決方案是:
public static Result up() throws IOException{
MultipartFormData body = request().body().asMultipartFormData();
List<FilePart> resourceFiles=body.getFiles();
InputStream input;
OutputStream output;
File part1;
String prefix,suffix;
for (FilePart picture:resourceFiles) {
part1 =picture.getFile();
input= new FileInputStream(part1);
prefix = FilenameUtils.getBaseName(picture.getFilename());
suffix = FilenameUtils.getExtension(picture.getFilename());
part1=new File("/home/rahul/Documents/upload",prefix+"."+suffix);
part1.createNewFile();
output = new FileOutputStream(part1);
IOUtils.copy(input, output);
Logger.info("Uploaded file successfully saved in " + part1.getAbsolutePath());
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.