[英]File download returns corrupted file (I think) in Play framework 2.2.2
我正在努力使文件上載/下載在Play框架2.2.2中正常工作。 我有一個名為“ cv”的學生班。 它用@Lob注釋,如下所示:
@Lob
public byte[] cv;
以下是上傳和下載方法:
public static Result upload() {
MultipartFormData body = request().body().asMultipartFormData();
FilePart cv = body.getFile("cv");
if (cv != null) {
filenameCV = cv.getFilename();
String contentType = cv.getContentType();
File file = cv.getFile();
Http.Session session = Http.Context.current().session();
String studentNr = session.get("user");
Student student = Student.find.where().eq("studentNumber", studentNr).findUnique();
InputStream is;
try {
is = new FileInputStream(file);
student.cv = IOUtils.toByteArray(is);
} catch (IOException e) {
Logger.debug("Error converting file");
}
student.save();
flash("ok", "Vellykket! Filen " + filenameCV + " ble lastet opp til din profil");
return redirect(routes.Profile.profile());
} else {
flash("error", "Mangler fil");
return redirect(routes.Profile.profile());
}
}
public static Result download() {
Http.Session session = Http.Context.current().session();
Student student = Student.find.where().eq("studentNumber", session.get("user")).findUnique();
File f = new File("/tmp/" +filenameCV);
FileOutputStream fos;
try {
fos = new FileOutputStream(f);
fos.write(student.cv);
fos.flush();
fos.close();
} catch(IOException e) {
}
return ok(f);
}
該文件似乎已正確保存到數據庫中(cv字段中填充了數據,但對我來說顯然是很隱秘的,因此我不確定內容是否應為預期內容)
當我進入網站並單擊“下載CV”鏈接(運行下載操作)時,文件已下載但無法打開-表示PDF查看器無法識別文件等。(上傳的文件必須是PDF)
有什么想法可能有問題嗎?
不要將文件保存在DB中,文件系統要好得多! 用一些唯一的名稱將上載的文件保存在磁盤上,然后在數據庫中僅將文件路徑保留為String
!
處理下載更容易,例如,在Play中,提供PDF所需的全部就是:
public static Result download() { File file = new File("/full/path/to/your.pdf"); return ok(file); }
它將不僅為PDF設置適當的標題,例如Content-Disposition
, Content-Length
和Content-Type
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.