Pergunta

I'm struggling with getting file upload/download to work properly in Play framework 2.2.2. I have a Student class with a field called "cv". It's annotated with @Lob, like this:

@Lob
public byte[] cv;

Here are the upload and download methods:

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);
}

The file seems to be correctly saved to the database (the cv field is populated with data, but it's obviously cryptic to me so I don't know for sure that the content is what it's supposed to be)

When I go to my website and click the "Download CV" link (which runs the download action), the file gets downloaded but can't be opened - saying the PDF viewer can't recognize the file etc. (Files uploaded have to be PDF)

Any ideas on what might be wrong?

Foi útil?

Solução

Don't keep your files in DB, filesystem is much better for that! Save uploaded file on the disk with some unique name, then in your database keep only path to the file as a String!

  • It's cheaper in longer run (as said many times)
  • It's easier to handle downloads, i.e. in Play all you need to serve PDF is:

    public static Result download() {
        File file = new File("/full/path/to/your.pdf");
        return ok(file);
    }
    

it will set proper headers, like Content-Disposition, Content-Length and Content-Type not only for PDFs

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top