上传大文件经常遇到上传一半由于网络或者其他一些原因上传失败。然后又得重新上传(很麻烦),所以就想能不能做个断点上传的功能。于是网上搜索,发现市面上很少有断点上传的案例,有找到一个案例也是采用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();
}
}
}
接口二代码如下:
@WebServlet(urlPatterns = { "/uploaderWithContinuinglyTransferring" })
public class UploaderServletWithContinuinglyTransferring extends HttpServlet {
private static final long serialVersionUID = 1L;
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();
System.out.println("临时目录:" + repositoryPath);
uploadPath = config.getServletContext().getRealPath("datas/uploader");
System.out.println("目录:" + uploadPath);
File up = new File(uploadPath);
if (!up.exists()) {
up.mkdir();
}
}
@SuppressWarnings("unchecked")
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setCharacterEncoding("UTF-8");
Integer schunk = null;// 分割块数
Integer schunks = null;// 总分割数
String name = null;// 文件名
BufferedOutputStream outputStream = null;
if (ServletFileUpload.isMultipartContent(request)) {
try {
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold(1024);
factory.setRepository(new File(repositoryPath));// 设置临时目录
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setHeaderEncoding("UTF-8");
upload.setSizeMax(5 * 1024 * 1024 * 1024);// 设置附近大小
List<FileItem> items = upload.parseRequest(request);
// 生成新文件名
String newFileName = null;
for (FileItem item : items) {
if (!item.isFormField()) {// 如果是文件类型
name = newFileName;// 获得文件名
if (name != null) {
String nFname = newFileName;
if (schunk != null) {
nFname = schunk + "_" + name;
}
File savedFile = new File(uploadPath, nFname);
item.write(savedFile);
}
} else {
// 判断是否带分割信息
if (item.getFieldName().equals("chunk")) {
schunk = Integer.parseInt(item.getString());
//System.out.println(schunk);
}
if (item.getFieldName().equals("chunks")) {
schunks = Integer.parseInt(item.getString());
}
if (item.getFieldName().equals("name")) {
newFileName = new String(item.getString());
}
}
}
//System.out.println(schunk + "/" + schunks);
if (schunk != null && schunk == 1) {
TfileUploadStatus file = statusService.get(newFileName);
if (file != null) {
statusService.updateChunk(newFileName, schunk);
} else {
statusService.add(newFileName, schunk, schunks);
}
} else {
TfileUploadStatus file = statusService.get(newFileName);
if (file != null) {
statusService.updateChunk(newFileName, schunk);
}
}
if (schunk != null && schunk.intValue() == schunks.intValue()) {
outputStream = new BufferedOutputStream(new FileOutputStream(new File(uploadPath, newFileName)));
// 遍历文件合并
for (int i = 1; i <= schunks; i++) {
//System.out.println("文件合并:" + i + "/" + schunks);
File tempFile = new File(uploadPath, i + "_" + name);
byte[] bytes = FileUtils.readFileToByteArray(tempFile);
outputStream.write(bytes);
outputStream.flush();
tempFile.delete();
}
outputStream.flush();
}
response.getWriter().write("{\"status\":true,\"newName\":\"" + newFileName + "\"}");
} catch (FileUploadException e) {
e.printStackTrace();
response.getWriter().write("{\"status\":false}");
} catch (Exception e) {
e.printStackTrace();
response.getWriter().write("{\"status\":false}");
} finally {
try {
if (outputStream != null)
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
关键点:
1 需要与数据库交互,数据库存放文件名,第几块,总共几块这几个字段
2 上传时先调用接口一,通过文件名查询数据,如果有数据,则表示接下来要续传,接着调用第二个接口进行上传剩下的文件块
3 如果没有数据则表示是新文件上传,调用接口二,从第一块开始上传,接口二主要作用记录并更新文件的上传信息(数据库数据),在满足当前上传区块等于总块数时进行合并文件。
另外数据库新建表可以执行如下数据库语句
DROP TABLE IF EXISTS sys_file_upload_status
;
CREATE TABLE sys_file_upload_status
(
obj_id
varchar(36) NOT NULL,
file_name
varchar(1000) DEFAULT NULL,
chunk
int(11) DEFAULT NULL,
chunks
int(11) DEFAULT NULL,
PRIMARY KEY (obj_id
)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
数据库交互大家使用自己熟悉的方式即可,比如jdbc,hibernate,mybatis等等,哪个好用用哪个。