java大文件断点续传
上传大文件经常遇到上传一半由于网络或者其他一些原因上传失败。然后又得重新上传(很麻烦),所以就想能不能做个断点上传的功能。于是网上搜索,发现市面上很少有断点上传的案例,有找到一个案例也是采用SOCKET作为上传方式(大文件上传,不适合使用POST,GET形式)。由于大文件夹不适合http上传的方式,所以就想能不能把大文件切割成n块小文件,然后上传这些小文件,所有小文件全部上传成功后再在服务器上进行拼接。这样不就可以实现断点上传,又解决了http不适合上传大文件的难题了吗!!!
服务端:
需要写两个接口
接口一:根据上传文件名称filename 判断是否之前上传过,没有则返回客户端chunck=1,有则读取记录chunck并返回。
接口二:上传文件,如果上传块数chunck=chuncks,遍历所有块文件拼接成一个完整文件。
接口一代码如下:
@WebServlet(urlPatterns = { "/ckeckFileServlet" })
public class CkeckFileServlet extends HttpServlet {
private FileUploadStatusServiceI statusService;
String repositoryPath;
String uploadPath;
@Override
public void init(ServletConfig config) throws ServletException {
ServletContext servletContext = config.getServletContext();
WebApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(servletContext);
statusService = (FileUploadStatusServiceI) context.getBean("fileUploadStatusServiceImpl");
repositoryPath = FileUtils.getTempDirectoryPath();
uploadPath = config.getServletContext().getRealPath("datas/uploader");
File up = new File(uploadPath);
if (!up.exists()) {
up.mkdir();
}
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// TODO Auto-generated method stub
String fileName = new String(req.getParameter("filename"));
//String chunk = req.getParameter("chunk");
//System.out.println(chunk);
System.out.println(fileName);
resp.setContentType("text/json; charset=utf-8");
TfileUploadStatus file = statusService.get(fileName);
try {
if (file != null) {
int schunk = file.getChunk();
deleteFile(uploadPath + schunk + "_" + fileName);
//long off = schunk * Long.parseLong(chunkSize);
resp.getWriter().write("{\"off\":" + schunk + "}");
} else {
resp.getWriter().write("{\"off\":1}");
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
接口二代码如下: