2014/03/21

FileDropJS 的 Java servier-side

最近要做drop file upload的系統,經過挑選,選擇了一個較light-weight的FileDrop (filedropjs.org)
不過它只有提供PHP server-side程式可參考,找了老半天,沒有看到Java的solution,於是只好自己來研究一下了
還好花一天的工就完成,在這裡做個記錄

protected void process(HttpServletRequest request, HttpServletResponse response) throws IOException {
PrintWriter writer = response.getWriter();
JSONObject obj = new JSONObject();

try {
saveRawDataToFile(request); // file upload by raw request

    obj.put(AbstractCommand.R_SUCCESS, true);
    obj.put(AbstractCommand.R_MSG, "upload completed");
} catch (IOException e) {
    obj.put(AbstractCommand.R_SUCCESS, false);
    obj.put(AbstractCommand.R_MSG, e.getMessage());
} finally {
    writer.println(obj.toString());
writer.flush();
}
}

protected void saveRawDataToFile(HttpServletRequest request) throws IOException {
String filename = request.getParameter("img") + ".png";
String outputFile = uploadPath + File.separator + filename;

InputStream in=request.getInputStream();
int size=request.getContentLength();

try {
OutputStream out=new FileOutputStream(outputFile);
byte[] chunk= new byte[size];
in.read(chunk);
out.write(chunk,0,size);
out.close();
} catch (Exception e) {
e.printStackTrace(System.out);
} finally {
in.close();
}
}