This is a servlet demo, for using Resumable.js to upload files. by fanxu123
| 16 | * by fanxu123 |
| 17 | */ |
| 18 | public class UploadServlet extends HttpServlet { |
| 19 | |
| 20 | public static final String UPLOAD_DIR = "e:\\"; |
| 21 | |
| 22 | protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { |
| 23 | int resumableChunkNumber = getResumableChunkNumber(request); |
| 24 | |
| 25 | ResumableInfo info = getResumableInfo(request); |
| 26 | |
| 27 | RandomAccessFile raf = new RandomAccessFile(info.resumableFilePath, "rw"); |
| 28 | |
| 29 | //Seek to position |
| 30 | raf.seek((resumableChunkNumber - 1) * info.resumableChunkSize); |
| 31 | |
| 32 | //Save to file |
| 33 | InputStream is = request.getInputStream(); |
| 34 | long readed = 0; |
| 35 | long content_length = request.getContentLength(); |
| 36 | byte[] bytes = new byte[1024 * 100]; |
| 37 | while(readed < content_length) { |
| 38 | int r = is.read(bytes); |
| 39 | if (r < 0) { |
| 40 | break; |
| 41 | } |
| 42 | raf.write(bytes, 0, r); |
| 43 | readed += r; |
| 44 | } |
| 45 | raf.close(); |
| 46 | |
| 47 | |
| 48 | //Mark as uploaded. |
| 49 | info.uploadedChunks.add(new ResumableInfo.ResumableChunkNumber(resumableChunkNumber)); |
| 50 | if (info.checkIfUploadFinished()) { //Check if all chunks uploaded, and change filename |
| 51 | ResumableInfoStorage.getInstance().remove(info); |
| 52 | response.getWriter().print("All finished."); |
| 53 | } else { |
| 54 | response.getWriter().print("Upload"); |
| 55 | } |
| 56 | } |
| 57 | |
| 58 | protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { |
| 59 | int resumableChunkNumber = getResumableChunkNumber(request); |
| 60 | |
| 61 | ResumableInfo info = getResumableInfo(request); |
| 62 | |
| 63 | if (info.uploadedChunks.contains(new ResumableInfo.ResumableChunkNumber(resumableChunkNumber))) { |
| 64 | response.getWriter().print("Uploaded."); //This Chunk has been Uploaded. |
| 65 | } else { |
| 66 | response.setStatus(HttpServletResponse.SC_NOT_FOUND); |
| 67 | } |
| 68 | } |
| 69 | |
| 70 | private int getResumableChunkNumber(HttpServletRequest request) { |
| 71 | return HttpUtils.toInt(request.getParameter("resumableChunkNumber"), -1); |
| 72 | } |
| 73 | |
| 74 | private ResumableInfo getResumableInfo(HttpServletRequest request) throws ServletException { |
| 75 | String base_dir = UPLOAD_DIR; |
nothing calls this directly
no outgoing calls
no test coverage detected