断点续传
功能需求:
保证传输时网络中断,在次选择同样的文件可以继续上传。
实现思路:
传输文件生成文件夹,通过File生成临时文件temp,
通过RandomAccessFile保证从传输的字节处写入临时文件。
功能关键点 RandomAccessFile
r:读模式
w:只写
rw:读写,如果使用此模式,如果此文件不存在,则会自动创建。 seek(0)就是定位到你文件的开头下一次写或者读就会从你定的位置开始。
eg:下面代码是我做的功能,分为客户端上传和管理员上传分别对应不同的操作,可以更改为其他需求。
网上SpringMVC版本最全的一篇。。
Controller
/**
* 倾斜摄影zip断点续传
* @param userName 用户名
* @param processType 客户端or管理员
* @param request
* @param response
* @return
* @throws IOException
* @author ygc
*/
@RequestMapping(value="/tiltPictureUpload")
@ResponseBody
public String TiltPictureUpload(@RequestParam("userName") String userName,@RequestParam("processType") String processType,HttpServletRequest request,
HttpServletResponse response) throws IOException {
response.setContentType("textml;charset=UTF-8");
response.setHeader("Content-type", "application/json;charset=UTF-8");
JsonResult jr = new JsonResult();
System.out.println("测试...");
boolean data = tiltPictureService.tiltPictureUpload(request,userName,processType);
Map<String, Object> result = new HashMap<String, Object>();
result.put("code", 0);
result.put("msg", "");
result.put("data", data);
// jr.setData("data", msg);
String r = JSON.toJSONString(result);
response.getWriter().print(r);
return null;
}
Service
/**
* 倾斜摄影zip断点续传
* @author ygc
*/
@Override
public boolean tiltPictureUpload(HttpServletRequest request, String userName, String processType) throws IOException {
//获取文件工厂实例
FileUploadFactory factory=new FileUploadFactory();
//如果是客户端
if(processType.equals("0")) {
//生产客户端文件产品
UploadService client= factory.getFileByClass("com.earthview.service.impl.ClientUpload");
boolean temp=client.breakPointUpload(request, userName, processType);
return temp;
//否则管理员
}else {
//生产管理员文件产品
UploadService manager=factory.getFileByClass("com.earthview.service.impl.ManagerUpload");
boolean temp=manager.breakPointUpload(request, userName, processType);
return temp;
}
}
ClientUpload
package com.earthview.service.impl;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItem;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import com.earthview.dao.TiltPictureDao;
import com.earthview.entity.TiltPicture;
import com.earthview.entity.TiltPictureAll;
import com.earthview.service.DataService;
import com.earthview.service.TiltPictureService;
import com.earthview.service.UploadService;
import com.earthview.util.Commons;
import com.earthview.util.DateUtil;
import com.earthview.util.SpringContextUtil;
import com.earthview.util.TiltUtil;
public class ClientUpload implements UploadService{
/**
* 客户端上传产品类
*/
@Override
public boolean breakPointUpload(HttpServletRequest request, String userName, String processType)
throws IOException {
System.out.println("客户端上传产品类..");
//创建解析器
MultipartHttpServletRequest mh=(MultipartHttpServletRequest) request;
//获得文件
// CommonsMultipartFile cmf=(CommonsMultipartFile) mh.getFile("uploadForm");
CommonsMultipartFile cmf=(CommonsMultipartFile) mh.getFile("file");
DiskFileItem fi = (DiskFileItem ) cmf.getFileItem();
File fs = fi.getStoreLocation();
//获得原始文件名
String oriName=cmf.getOriginalFilename();
String uuid=UUID.randomUUID().toString();
String directory=Commons.TILTPICTURE_PATH;
String savePath=Commons.TILTPICTURE_PATH+File.separator+userName+"-"+uuid;
//status=0正在上传
String uploadStatus;
//status=0未下载
String downloadStatus;
String targetFilePath=Commons.TILTPICTURE_TARGET_PATH;
FileItem fileItem=cmf.getFileItem();
int allSize=(int) fileItem.getSize();
if(oriName.matches(".*.zip") || oriName.matches(".*.rar")){
//查询倾斜影像信息通过文件名
TiltPictureDao tiltPictureDao = (TiltPictureDao) SpringContextUtil.getBean("tiltPictureDao");
TiltPicture tiltList=tiltPictureDao.findTiltPictureInfoByName(oriName);
if(tiltList.getFileName()==null ){
if(!"1".equals(tiltList.getUploadStatus()) && !"0".equals(tiltList.getDownloadStatus())) {
File directoryPath=new File(directory);
if (!directoryPath.exists() && !directoryPath.isDirectory()) {
directoryPath.mkdir();
}
File filePath=new File(savePath);
if (!filePath.exists() && !filePath.isDirectory()) {
filePath.mkdir();
}
//文件未上传过正常上传
File file=new File(savePath,oriName+".temp");
if(!file.exists()) {
file.createNewFile();
}
DataInputStream dis=new DataInputStream(fileItem.getInputStream());
// DataOutputStream dos=new DataOutputStream(fileItem.getOutputStream());
RandomAccessFile w=new RandomAccessFile(file, "rw");
RandomAccessFile r=new RandomAccessFile(fs, "rw");
// //获得文件大小
long size=0;
if(file.exists()&&file.isFile()){
size=file.length();
}
//保存上传文件信息 状态1为正在上传
// tiltPictureDao.saveUploadFileInfo(oriName,savePath,uploadStatus="1",allSize,downloadStatus="0",targetFilePath);
w.seek(size);
r.seek(size);
int length;
byte[] buf=new byte[512];
while((length=r.read(buf, 0, buf.length))!=-1){
w.write(buf,0,length);
}
int barOffset=(int)(w.length()/1024);
int barSize=(int)(allSize/1024);
// //修改名称
if (barOffset>=barSize) {
w.close();
r.close();
dis.close();
// dos.close();
file.renameTo(new File(savePath,oriName));
System.out.println(oriName);
// //修改状态为2 上传完成
// tiltPictureDao.updateUploadFileStatus(uploadStatus="2",oriName);
String uploadTime=DateUtil.dateToString1();
tiltPictureDao.saveUploadFileInfo(oriName,savePath,uploadStatus="1",allSize,downloadStatus="0","",userName,uploadTime);
}
try {
} catch (Exception e){
e.printStackTrace();
}
}
return true;
//--
}
else{
String deletePath;
if(tiltList.getFilePath()!=null && !tiltList.getFilePath().equals("")) {
deletePath=tiltList.getFilePath();
}else {
deletePath=tiltList.getTargetFilePath();
}
//上传完成 重现新上传删除原文件
// tiltPictureDao.deleteUploadFileStatus(uploadStatus="1",oriName);
tiltPictureDao.deleteUploadFileStatus(oriName);
String deleteFilePath=deletePath+"\\"+oriName;
//删除文件
TiltUtil.delFile(deleteFilePath);
//删除目录
TiltUtil.delFile(deletePath);
File directoryPath=new File(directory);
if (!directoryPath.exists() && !directoryPath.isDirectory()) {
directoryPath.mkdir();
}
File filePath=new File(savePath);
if (!filePath.exists() && !filePath.isDirectory()) {
filePath.mkdir();
}
File file=new File(savePath,oriName+".temp");
if(file.exists()) {
file.createNewFile();
}
DataInputStream dis=new DataInputStream(fileItem.getInputStream());
// DataOutputStream dos=new DataOutputStream(fileItem.getOutputStream());
RandomAccessFile w=new RandomAccessFile(file, "rw");
RandomAccessFile r=new RandomAccessFile(fs, "rw");
// //获得文件大小
long size=0;
if(file.exists()&&file.isFile()){
size=file.length();
}
//保存上传文件信息 状态1为正在处理
// tiltPictureDao.saveUploadFileInfo(oriName,savePath,uploadStatus="1",allSize,downloadStatus="0",targetFilePath);
w.seek(size);
r.seek(size);
int length;
byte[] buf=new byte[512];
while((length=r.read(buf, 0, buf.length))!=-1){
w.write(buf,0,length);
}
int barSize=(int)(w.length()/1024);
int barOffset=(int)(allSize/1024);
// //修改名称
if (barOffset>=barSize) {
w.close();
r.close();
dis.close();
// dos.close();
file.renameTo(new File(savePath,oriName));
System.out.println(oriName);
//状态为1 上传完成
//tiltPictureDao.updateUploadFileStatus(uploadStatus="2",oriName);
String uploadTime=DateUtil.dateToString1();
tiltPictureDao.saveUploadFileInfo(oriName,savePath,uploadStatus="1",allSize,downloadStatus="0","",userName,uploadTime);
}
try {
} catch (Exception e){
e.printStackTrace();
}
return true;
}
}else {
return false;
}
}
}
ManagerUpload
package com.earthview.service.impl;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.List;
import java.util.UUID;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItem;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import com.earthview.dao.TiltPictureDao;
import com.earthview.entity.TiltPicture;
import com.earthview.entity.TiltPictureAll;
import com.earthview.service.TiltPictureService;
import com.earthview.service.UploadService;
import com.earthview.util.Commons;
import com.earthview.util.DateUtil;
import com.earthview.util.SpringContextUtil;
import com.earthview.util.TiltUtil;
public class ManagerUpload implements UploadService{
/**
* 管理员上传文件产品类
*/
public boolean breakPointUpload(HttpServletRequest request, String userName, String processType)
throws IOException {
System.out.println("管理员上传产品类..");
//创建解析器
MultipartHttpServletRequest mh=(MultipartHttpServletRequest) request;
//获得文件
CommonsMultipartFile cmf=(CommonsMultipartFile) mh.getFile("file");
DiskFileItem fi = (DiskFileItem ) cmf.getFileItem();
File fs = fi.getStoreLocation();
//获得原始文件名
String oriName=cmf.getOriginalFilename();
String uuid=UUID.randomUUID().toString();
String directory=Commons.MANAGER_TILTPICTURE_TARGET_PATH;
String savePath=Commons.MANAGER_TILTPICTURE_TARGET_PATH+File.separator+userName+"-"+uuid;
//status=0正在上传
String uploadStatus;
//status=0未下载
String downloadStatus;
String targetFilePath=Commons.TILTPICTURE_TARGET_PATH;
FileItem fileItem=cmf.getFileItem();
int allSize=(int) fileItem.getSize();
if(oriName.matches(".*.zip") || oriName.matches(".*.rar")){
//查询倾斜影像信息通过文件名
TiltPictureDao tiltPictureDao = (TiltPictureDao) SpringContextUtil.getBean("tiltPictureDao");
TiltPicture tiltList=tiltPictureDao.findTiltPictureInfoByName(oriName);
if(tiltList.getFileName()==null ){
if(!"2".equals(tiltList.getUploadStatus()) && !"0".equals(tiltList.getDownloadStatus())) {
File directoryPath=new File(directory);
if (!directoryPath.exists() && !directoryPath.isDirectory()) {
directoryPath.mkdir();
}
//判断子文件夹是否存在
File filePath=new File(savePath);
if (!filePath.exists() && !filePath.isDirectory()) {
filePath.mkdir();
}
//文件未上传过正常上传
File file=new File(savePath,oriName+".temp");
if(!file.exists()) {
file.createNewFile();
}
DataInputStream dis=new DataInputStream(fileItem.getInputStream());
// DataOutputStream dos=new DataOutputStream(fileItem.getOutputStream());
RandomAccessFile w=new RandomAccessFile(file, "rw");
RandomAccessFile r=new RandomAccessFile(fs, "rw");
// File file1=new File(oriName);
// RandomAccessFile raw=new RandomAccessFile(file1, "rw");
//
long size=0;
if(file.exists()&&file.isFile()){
size=file.length();
}
//保存上传文件信息 状态1为正在上传 1703 10427
// tiltPictureDao.saveUploadFileInfo(oriName,savePath,uploadStatus="1",allSize,downloadStatus="0",targetFilePath);
int length;
w.seek(size);
r.seek(size);
// raw.seek(size);
// 数据缓冲区
byte[] buf = new byte[2048];
while((length=r.read(buf, 0, buf.length))!=-1){
w.write(buf,0,length);
}
int barOffset=(int)(w.length()/1024);
int barSize=(int)(allSize/1024);
// //修改名称
if (barOffset>=barSize) {
w.close();
r.close();
dis.close();
// dos.close();
file.renameTo(new File(savePath,oriName));
System.out.println(oriName);
//管理员状态为2 处理完成
String uploadTime=DateUtil.dateToString1();
tiltPictureDao.saveUploadFileInfo(oriName,"",uploadStatus="2",allSize,downloadStatus="0",savePath,userName,uploadTime);
}
try {
} catch (Exception e){
e.printStackTrace();
}
}
return true;
//--
}else{
String deletePath;
if(tiltList.getFilePath()!=null && !tiltList.getFilePath().equals("")) {
deletePath=tiltList.getFilePath();
}else {
deletePath=tiltList.getTargetFilePath();
}
//上传完成 重现新上传删除原文件
tiltPictureDao.deleteUploadFileStatus(oriName);
String deleteFilePath=deletePath+"\\"+oriName;
File file=new File(savePath,oriName+".temp");
//删除文件
TiltUtil.delFile(deleteFilePath);
//删除目录
TiltUtil.delFile(deletePath);
File directoryPath=new File(directory);
if (!directoryPath.exists() && !directoryPath.isDirectory()) {
directoryPath.mkdir();
}
File filePath=new File(savePath);
if (!filePath.exists() && !filePath.isDirectory()) {
filePath.mkdir();
}
if(file.exists()) {
file.createNewFile();
}
DataInputStream dis=new DataInputStream(fileItem.getInputStream());
// DataOutputStream dos=new DataOutputStream(fileItem.getOutputStream());
RandomAccessFile w=new RandomAccessFile(file, "rw");
RandomAccessFile r=new RandomAccessFile(fs, "rw");
// //获得文件大小
long size=0;
if(file.exists()&&file.isFile()){
size=file.length();
}
//保存上传文件信息 状态1为正在处理
// tiltPictureDao.saveUploadFileInfo(oriName,savePath,uploadStatus="1",allSize,downloadStatus="0",targetFilePath);
int length;
w.seek(size);
r.seek(size);
// 数据缓冲区
byte[] buf = new byte[2048];
while((length=r.read(buf, 0, buf.length))!=-1){
w.write(buf,0,length);
}
int barOffset=(int)(w.length()/1024);
int barSize=(int)(allSize/1024);
// //修改名称
if (barOffset>=barSize) {
r.close();
w.close();
dis.close();
// dos.close();
file.renameTo(new File(savePath,oriName));
System.out.println(oriName);
// //修改状态为2 上传完成
// tiltPictureDao.updateUploadFileStatus(uploadStatus="2",oriName);
String uploadTime=DateUtil.dateToString1();
tiltPictureDao.saveUploadFileInfo(oriName,"",uploadStatus="2",allSize,downloadStatus="0",savePath,userName,uploadTime);
}
try {
} catch (Exception e){
e.printStackTrace();
}
return true;
}
}else {
return false;
}
}
}
Dao SpringJDBC
package com.earthview.dao;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Component;
import com.earthview.entity.Event;
import com.earthview.entity.TiltPicture;
import com.earthview.entity.TiltPictureAll;
import com.earthview.util.BaseDao;
@Component
public class TiltPictureDao extends BaseDao {
//保存上传文件信息 状态1为正在处理
public int saveUploadFileInfo(String fileName, String filePath, String uploadStatus, long fileSize, String downloadStatus, String targetFilePath, String userName, String uploadTime) {
Map<String, Object> paramMap = new HashMap<String, Object>();
paramMap.put("fileName", fileName);
paramMap.put("filePath", filePath);
paramMap.put("uploadStatus", uploadStatus);
paramMap.put("fileSize", fileSize);
paramMap.put("downloadStatus", downloadStatus);
paramMap.put("targetFilePath", targetFilePath);
paramMap.put("userName", userName);
paramMap.put("uploadTime", uploadTime);
String sql="insert into exhibit_ev_tilt_upload (fileName,filePath,uploadStatus,fileSize,downloadStatus,targetFilePath,userName,uploadTime) values (:fileName,:filePath,:uploadStatus,:fileSize,:downloadStatus,:targetFilePath,:userName,:uploadTime)";
return this.getNamedParameterJdbcTemplate().update(sql, paramMap);
}
public int updateUploadFileStatus(String uploadStatus, String fileName) {
Map<String, Object> paramMap = new HashMap<String, Object>();
paramMap.put("uploadStatus", uploadStatus);
paramMap.put("fileName", fileName);
String sql="update exhibit_ev_tilt_upload set uploadStatus=:uploadStatus where fileName=:fileName ";
return this.getNamedParameterJdbcTemplate().update(sql, paramMap);
}
public TiltPicture findTiltPictureInfoByName(String fileName) {
Map<String, Object> paramMap = new HashMap<String, Object>();
TiltPicture data=new TiltPicture();
paramMap.put("fileName", fileName);
String sql="select * from exhibit_ev_tilt_upload where fileName=:fileName";
try {
return getNamedParameterJdbcTemplate().queryForObject(sql, paramMap, rowMapper1);
} catch (EmptyResultDataAccessException e) {
// TODO: handle exception
return data;
}
}
private RowMapper<TiltPicture> rowMapper1 = new RowMapper<TiltPicture>() {
@Override
public TiltPicture mapRow(ResultSet rs, int arg1) throws SQLException {
TiltPicture data = new TiltPicture();
if(rs.getObject("fileName")!=null) {
data.setFileName(rs.getString("fileName"));
}
if(rs.getObject("filePath")!=null) {
data.setFilePath(rs.getString("filePath"));
}
if(rs.getObject("uploadStatus")!=null) {
data.setUploadStatus(rs.getString("uploadStatus"));
}
if(rs.getObject("fileSize")!=null){
data.setFileSize(rs.getInt("fileSize"));
}
if(rs.getObject("downloadStatus")!=null){
data.setDownloadStatus(rs.getString("downloadStatus"));
}
if(rs.getObject("uploadTime")!=null){
data.setUploadTime(rs.getString("uploadTime"));
}
if(rs.getObject("userName")!=null){
data.setUserName(rs.getString("userName"));
}
if(rs.getObject("targetFilePath")!=null){
data.setTargetFilePath(rs.getString("targetFilePath"));
}
if(rs.getObject("downloadDate")!=null){
data.setDownloadDate(rs.getString("downloadDate"));
}
return data;
}
};
public int deleteUploadFileStatus(String fileName) {
Map<String, Object> paramMap = new HashMap<String, Object>();
// paramMap.put("uploadStatus",uploadStatus);
paramMap.put("fileName",fileName);
// String sql="delete from exhibit_ev_tilt_upload where fileName=:fileName and uploadStatus=:uploadStatus";
String sql="delete from exhibit_ev_tilt_upload where fileName=:fileName ";
return this.getNamedParameterJdbcTemplate().update(sql, paramMap);
}
public List<TiltPicture> findTiltPictureUploadStatusByName(String userName) {
Map<String, Object> paramMap = new HashMap<String, Object>();
paramMap.put("userName", userName);
String sql="select fileName,uploadStatus,downloadStatus,fileSize from exhibit_ev_tilt_upload where userName=:userName";
return this.getNamedParameterJdbcTemplate().query(sql, paramMap, rowMapper2);
}
private RowMapper<TiltPicture> rowMapper2 = new RowMapper<TiltPicture>() {
@Override
public TiltPicture mapRow(ResultSet rs, int arg1) throws SQLException {
TiltPicture data = new TiltPicture();
if(rs.getObject("fileName")!=null) {
data.setFileName(rs.getString("fileName"));
}
if(rs.getObject("uploadStatus")!=null) {
data.setUploadStatus(rs.getString("uploadStatus"));
}
if(rs.getObject("downloadStatus")!=null) {
data.setDownloadStatus(rs.getString("downloadStatus"));
}
if(rs.getObject("fileSize")!=null) {
data.setFileSize(rs.getInt("fileSize"));
}
return data;
}
};
public TiltPicture findUploadStatusByName(String fileName) {
Map<String, Object> paramMap = new HashMap<String, Object>();
paramMap.put("fileName", fileName);
String sql="select fileName,uploadStatus,filePath,targetFilePath from exhibit_ev_tilt_upload where fileName=:fileName";
return this.getNamedParameterJdbcTemplate().queryForObject(sql, paramMap, rowMapper3);
}
private RowMapper<TiltPicture> rowMapper3 = new RowMapper<TiltPicture>() {
@Override
public TiltPicture mapRow(ResultSet rs, int arg1) throws SQLException {
TiltPicture data = new TiltPicture();
if(rs.getObject("fileName")!=null) {
data.setFileName(rs.getString("fileName"));
}
if(rs.getObject("uploadStatus")!=null) {
data.setUploadStatus(rs.getString("uploadStatus"));
}
if(rs.getObject("filePath")!=null) {
data.setFilePath(rs.getString("filePath"));
}
if(rs.getObject("targetFilePath")!=null){
data.setTargetFilePath(rs.getString("targetFilePath"));
}
return data;
}
};
public int findResultCount() {
Map<String, Object> paramMap = new HashMap<String, Object>();
String sql="select count(1) from exhibit_ev_tilt_upload ";
return this.getNamedParameterJdbcTemplate().queryForInt(sql, paramMap);
}
public List<TiltPictureAll> findResultCountListData(int startIndex, int pageSize) {
Map<String, Object> paramMap = new HashMap<String, Object>();
String sql = " SELECT "
+" t1.id,"
+" t1.fileName, "
+" t1.filePath, "
+" t1.targetFilePath,"
+" CASE "
+" WHEN t1.uploadStatus LIKE '%0%' THEN "
+" '正在上传' "
+" WHEN t1.uploadStatus LIKE '%1%' THEN "
+" '上传完成' "
+" WHEN t1.uploadStatus LIKE '%3%' THEN "
+" '下载完成' "
+" WHEN t1.uploadStatus LIKE '%4%' THEN "
+" '正在处理' "
+" WHEN t1.uploadStatus LIKE '%2%' THEN "
+" '处理完成' ELSE NULL "
+" END AS uploadStatus, "
// +" t1.fileSize, "
+" CASE "
+" "
+" WHEN t1.downloadStatus LIKE '%0%' THEN "
+" '未下载' "
+" WHEN t1.downloadStatus LIKE '%1%' THEN "
+" '已下载' ELSE NULL "
+" END AS downloadStatus "
+" FROM "
+" exhibit_ev_tilt_upload t1 LIMIT "+startIndex+","+pageSize;
// String sql="select t1.fileName,filePath,t1.uploadStatus,t1.fileSize,t1.downloadStatus from exhibit_ev_tilt_upload t1 LIMIT "+startIndex+","+pageSize ;
return this.getNamedParameterJdbcTemplate().query(sql, paramMap, rowMapper4);
}
private RowMapper<TiltPictureAll> rowMapper4 = new RowMapper<TiltPictureAll>() {
@Override
public TiltPictureAll mapRow(ResultSet rs, int arg1) throws SQLException {
TiltPictureAll data = new TiltPictureAll();
if(rs.getObject("id")!=null) {
data.setId(rs.getInt("id"));
}
if(rs.getObject("fileName")!=null) {
data.setFileName(rs.getString("fileName"));
}
if(rs.getObject("filePath")!=null) {
data.setFilePath(rs.getString("filePath"));
}
if(rs.getObject("uploadStatus")!=null) {
data.setUploadStatus(rs.getString("uploadStatus"));
}
// if(rs.getObject("fileSize")!=null){
// data.setFileSize(rs.getInt("fileSize"));
// }
if(rs.getObject("downloadStatus")!=null){
data.setDownloadStatus(rs.getString("downloadStatus"));
}
if(rs.getObject("targetFilePath")!=null){
data.setTargetFilePath(rs.getString("targetFilePath"));
}
// if(rs.getObject("uploadTime")!=null){
// data.setUploadTime(rs.getString("uploadTime"));
// }
// if(rs.getObject("userName")!=null){
// data.setUserName(rs.getString("userName"));
// }
return data;
}
};
public int updateDownloadStatusByName(String fileName, String downloadDate, String uploadStatus) {
Map<String, Object> paramMap = new HashMap<String, Object>();
paramMap.put("fileName",fileName);
paramMap.put("downloadDate",downloadDate);
paramMap.put("uploadStatus",uploadStatus);
String sql="update exhibit_ev_tilt_upload set downloadStatus=1,downloadDate=:downloadDate,uploadStatus=:uploadStatus where fileName=:fileName";
return this.getNamedParameterJdbcTemplate().update(sql, paramMap);
}
public int updateChangeDownloadStatusByName(String fileName, String downloadStatus, String downloadDate) {
Map<String, Object> paramMap = new HashMap<String, Object>();
paramMap.put("fileName",fileName);
paramMap.put("downloadStatus",downloadStatus);
paramMap.put("downloadDate",downloadDate);
String sql="update exhibit_ev_tilt_upload set downloadStatus=:downloadStatus,downloadDate=:downloadDate where fileName=:fileName";
return this.getNamedParameterJdbcTemplate().update(sql, paramMap);
}
public TiltPicture findCheckUploadStatusByUserName(String userName, String fileName) {
TiltPicture data=new TiltPicture();
Map<String, Object> paramMap = new HashMap<String, Object>();
paramMap.put("userName",userName);
paramMap.put("fileName",fileName);
String sql="select uploadStatus from exhibit_ev_tilt_upload where userName=:userName and fileName=:fileName";
try {
return getNamedParameterJdbcTemplate().queryForObject(sql, paramMap, rowMapper5);
} catch (EmptyResultDataAccessException e) {
// TODO: handle exception
return data;
}
}
private RowMapper<TiltPicture> rowMapper5 = new RowMapper<TiltPicture>() {
@Override
public TiltPicture mapRow(ResultSet rs, int arg1) throws SQLException {
TiltPicture data = new TiltPicture();
if(rs.getObject("uploadStatus")!=null) {
data.setUploadStatus(rs.getString("uploadStatus"));
}
return data;
}
};
}
FileUploadFactory
package com.earthview.service.impl;
import com.earthview.service.UploadService;
/**
* 文件上传工厂方法
* @author ygc
*/
public class FileUploadFactory {
//反射实现
public UploadService getFileByClass(String className){
UploadService type;
try {
type = (UploadService) Class.forName(className).newInstance();
return type;
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
util 删除指定路径文件或文件夹
/**
* 删除指定路径文件
* eg:c:/ygc.txt
* @param filePathAndName
*/
public static void delFile(String filePathAndName) {
try {
String filePath = filePathAndName;
filePath = filePath.toString();
java.io.File myDelFile = new java.io.File(filePath);
myDelFile.delete();
} catch (Exception e) {
System.out.println("删除文件操作出错");
e.printStackTrace();
}
}
}
获取Bean工具
/**
* 类名称:SpringContextUtil.java
*
* 类描述:
*
* 创建时间: 2015-4-23 上午10:32:51
*
**/
package com.earthview.util;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
public class SpringContextUtil implements ApplicationContextAware{
private static ApplicationContext applicationContext;
/**
* 实现ApplicationContextAware接口的回调方法,设置上下文环境
*/
public void setApplicationContext(ApplicationContext applicationContext){
SpringContextUtil.applicationContext = applicationContext;
}
public static ApplicationContext getApplicationContext(){
return applicationContext;
}
public static Object getBean(String name) throws BeansException{
return applicationContext.getBean(name);
}
}
//简化版例子。
package com.kero99.ygc.util;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
public class Test {
private static int position = -1;
public static void main(String[] args) {
// 源文件与目标文件
File sourceFile = new File("D:/", "test.txt");
File targetFile = new File("E:/", "test.txt");
// 输入输出流
FileInputStream fis = null;
FileOutputStream fos = null;
// 数据缓冲区
byte[] buf = new byte[1];
try {
fis = new FileInputStream(sourceFile);
fos = new FileOutputStream(targetFile);
// 数据读写
while (fis.read(buf) != -1) {
fos.write(buf);
// 当已经上传了3字节的文件内容时,网络中断了,抛出异常
if (targetFile.length() == 3) {
position = 3;
throw new FileAccessException();
}
}
} catch (FileAccessException e) {
keepGoing(sourceFile,targetFile, position);
} catch (FileNotFoundException e) {
System.out.println("指定文件不存在");
} catch (IOException e) {
// TODO: handle exception
} finally {
try {
// 关闭输入输出流
if (fis != null)
fis.close();
if (fos != null)
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private static void keepGoing(File source,File target, int position) {
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
RandomAccessFile readFile = new RandomAccessFile(source, "rw");
RandomAccessFile writeFile = new RandomAccessFile(target, "rw");
readFile.seek(position);
writeFile.seek(position);
// 数据缓冲区
byte[] buf = new byte[1];
// 数据读写
while (readFile.read(buf) != -1) {
writeFile.write(buf);
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
class FileAccessException extends Exception {
}
html+js
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<#assign static_url="/20180926_V1.0_GIS/media"/>
<script type="text/javascript" src="${static_url}/js/jquery-1.9.1.js"></script>
<script type="text/javascript">
function uploadFile(){
$("#check_upload").attr("disabled","disabled");
var name="于公成";
var type="1";
$.ajax({
type : "POST",
cache : false,
dataType : "json",
data:new FormData($('#file')[0]),
processData: false,//用于对data参数进行序列化处理 这里必须false
contentType: false, //必须 ?Year="+Year+"&quarter="+quarter"
url : "/20180926_V1.0_GIS/tilt/tiltPictureUpload.htm?userName="+name+"&&processType="+type+" ",
success : function(obj) {
/* alert(obj.data.msg); */
var result=obj.data.msg;
if(result==true){
$("#check_upload").removeAttr("disabled");
$("#checkResult").text("上传成功!").css("color","blue");
}else{
$("#check_upload").removeAttr("disabled");
$("#checkResult").text("上传失败!").css("color","red");
}
}
});
}
</script>
<form id="uploadForm" action="/url" >
<span>ZIP:</span> <input type="file" style="width: 170px" name="uploadForm" /><span id="checkResult"></span>
<input type="button" id="check_upload" value="确认上传" οnclick="uploadFile()"/>
</form>
<button id="toStop">暂停一下</button>
<button id="toStart">再次开始</button>
</body>
</html>
|