文件下载
/*
* 下载文件
*/
public void downloadFile(String proname, String fileName, HttpServletResponse resp) {
try {
ProjectEntity projectEntity = projectMapping.getProjectByName(proname);
ProductEntity productEntity = productMapping.getProductByProductId(projectEntity.getProProductId());
ProductOutsourceEntity productOutsourceEntity = productOutsourceMapping.getProductOutsourceByOutId(productEntity.getOutId());
//获取文件名
String strUrl = productOutsourceEntity.getFileUrl();
String filename = strUrl.substring(strUrl.lastIndexOf("/")+1);
filename = new String(filename.getBytes("iso8859-1"),"UTF-8");
String path = strUrl;
File file = new File(path);
//如果文件不存在
if(!file.exists()){
log.info("下载文件不存在");
}
//解决下载文件时文件名乱码问题
byte[] fileNameBytes = filename.getBytes(StandardCharsets.UTF_8);
filename = new String(fileNameBytes, 0, fileNameBytes.length, StandardCharsets.ISO_8859_1);
resp.reset();
resp.setContentType("application/octet-stream");
resp.setCharacterEncoding("utf-8");
resp.setContentLength((int) file.length());
//设置响应头,控制浏览器下载该文件
resp.setHeader("content-disposition", "attachment;filename=" + filename);
try{
//读取要下载的文件,保存到文件输入流
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(path));
//创建输出流
OutputStream os = resp.getOutputStream();
//缓存区
byte[] buff = new byte[1024];
int i = 0;
//循环将输入流中的内容读取到缓冲区中
while ((i = bis.read(buff)) != -1) {
os.write(buff, 0, i);
os.flush();
}
//关闭
bis.close();
os.close();
} catch (IOException e) {
log.error("{}",e);
log.info("下载失败");
}
log.info("下载成功");
} catch (Exception e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
}
文件夹下载
与文件下载不一样,需要先压缩再下载。本例子的服务器中文件URL已知,所以未用mapping层查询数据库,可根据需要加上。
Service:
/*
* 下载文件夹
*/
public void downloadFile(String proname, String fileName, HttpServletResponse resp) {
try {
//下载后的文件
String name=Constants.FILEPATH + Constants.PROJECT + proname + "/product/outsource"+".zip";
zipUtil zc = new zipUtil(name);
List<String> list=new ArrayList<>();
//服务器存储的URL
list.add(Constants.FILEPATH + Constants.PROJECT + proname + "/product/outsource");
//可继续添加要一起压缩的文件夹或文件
//list.add("");
String[] strings = new String[list.size()];
list.toArray(strings);
File file=null;
try {
zc.compress(strings);//压缩
file=new File(name);
downLoad.downloadZip(file,resp);//下载
} catch (IOException e) {
e.printStackTrace();
}finally {
if(file!=null){
file.delete();//把生成的压缩文件删除
}
}
} catch (Exception e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
}
Utile:
建立两个工具包
(1)压缩文件夹
public class ZipCompressorUtil {
static final int BUFFER = 8192;
/**
* 压缩的文件夹
*/
private File zipFile1111;
public ZipCompressorUtil(String pathName) {
zipFile1111 = new File(pathName);
}
/**
* 遍历需要压缩文件集合
* @param pathName
* @throws IOException
*/
public void compress(String... pathName) throws IOException {
ZipOutputStream out =null;
FileOutputStream fileOutputStream=null;
CheckedOutputStream cos=null;
try {
fileOutputStream = new FileOutputStream(zipFile1111);
cos = new CheckedOutputStream(fileOutputStream,new CRC32());
out = new ZipOutputStream(cos);
String basedir = "";
for (int i=0;i<pathName.length;i++){
compress(new File(pathName[i]), out, basedir);
}
} catch (Exception e) {
throw new RuntimeException(e);
}finally {
if(out!=null){
out.close();
}
if(fileOutputStream!=null){
fileOutputStream.close();
}
if(cos!=null){
cos.close();
}
}
}
/**
* 压缩
* @param file
* @param out
* @param basedir
*/
private void compress(File file, ZipOutputStream out, String basedir) throws IOException {
// 判断是目录还是文件
if (file.isDirectory()) {
this.compressDirectory(file, out, basedir);
} else {
this.compressFile(file, out, basedir);
}
}
/**
* 压缩一个目录
* */
private void compressDirectory(File dir, ZipOutputStream out, String basedir) throws IOException {
if (!dir.exists()){
return;
}
File[] files = dir.listFiles();
for (int i = 0; i < files.length; i++) {
// 递归
compress(files[i], out, basedir + dir.getName() + "/");
}
}
/**
* 压缩一个文件
*
* */
private void compressFile(File file, ZipOutputStream out, String basedir) throws IOException {
if (!file.exists()) {
return;
}
BufferedInputStream bis =null;
try {
bis = new BufferedInputStream(new FileInputStream(file));
ZipEntry entry = new ZipEntry(basedir + file.getName());
out.putNextEntry(entry);
int count;
byte[] data = new byte[BUFFER];
while ((count = bis.read(data, 0, BUFFER)) != -1) {
out.write(data, 0, count);
}
} catch (Exception e) {
throw new RuntimeException(e);
}finally {
if(bis!=null){
bis.close();
}
}
}
}
(2)下载文件夹
public class DownLoadUtil {
/**
* 下载压缩包
* @param file
* @param response
* @return
*/
public static HttpServletResponse downloadZip(File file,HttpServletResponse response) {
InputStream fis = null;
OutputStream toClient = null;
try {
// 以流的形式下载文件。
fis = new BufferedInputStream(new FileInputStream(file.getPath()));
byte[] buffer = new byte[fis.available()];
fis.read(buffer);
// 清空response
response.reset();
toClient = new BufferedOutputStream(response.getOutputStream());
response.setContentType("application/octet-stream");
//如果输出的是中文名的文件,在此处就要用URLEncoder.encode方法进行处理
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(file.getName(), "UTF-8"));
toClient.write(buffer);
toClient.flush();
} catch (IOException ex) {
ex.printStackTrace();
}finally{
try {
File f = new File(file.getPath());
f.delete();
if(fis!=null){
fis.close();
}
if(toClient!=null){
toClient.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
return response;
}
}
文件删除
/**
* 删除文件
* @param fileName
* @return
*/
public static boolean deleteFile(String fileName) {
File file = new File(fileName);
// 如果文件路径只有单个文件
if (file.exists() && file.isFile()) {
if (file.delete()) {
System.out.println("删除文件" + fileName + "成功!");
return true;
} else {
System.out.println("删除文件" + fileName + "失败!");
return false;
}
} else {
System.out.println(fileName + "不存在!");
return false;
}
}
文件夹删除
/**
* 删除文件夹,里面用到了删除文件的函数,把上面文件删除的函数也引进来
*/
public static boolean deleteAllFile(String dir) {
// 如果dir不以文件分隔符结尾,自动添加文件分隔符
if (!dir.endsWith(File.separator))
dir = dir + File.separator;
File dirFile = new File(dir);
// 如果dir对应的文件不存在,或者不是一个目录,则退出
if ((!dirFile.exists()) || (!dirFile.isDirectory())) {
System.out.println("删除文件夹失败:" + dir + "不存在!");
return false;
}
boolean flag = true;
// 删除文件夹中的所有文件包括子文件夹
File[] files = dirFile.listFiles();
for (int i = 0; i < files.length; i++) {
// 删除子文件
if (files[i].isFile()) {
flag = deleteFile(files[i].getAbsolutePath());
if (!flag)
break;
}
// 删除子文件夹
else if (files[i].isDirectory()) {
flag = deleteAllFile(files[i].getAbsolutePath());
if (!flag)
break;
}
}
if (!flag) {
System.out.println("删除文件夹失败!");
return false;
}
// 删除当前文件夹
if (dirFile.delete()) {
System.out.println("删除文件夹" + dir + "成功!");
return true;
} else {
return false;
}
}
文件上传(文件夹需自行压缩)
public String insertProductOutsource(ProductOutsourceEntity productOutsourceEntity,String proname, List<MultipartFile> file,HttpServletRequest req) {
// 判断参数有没有效
if(productOutsourceEntity == null) {
return Constants.FAILCODE;
}
try {
//获取当前时间
Calendar calendar = Calendar.getInstance();
String nowTime = (new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss").format(calendar.getTime()));
// 创建文件夹,文件名称与提交时间关联
ProjectEntity projectEntity = projectMapping.getProjectByName(proname);
String poId = signMapping.getSignById(projectEntity.getProSignId()).getPoId();
String docPath = Constants.FILEPATH + Constants.PROJECT + proname + "/product/" + poId + "-outsource/"+nowTime+"/";
File localPath = new File(docPath);
if (!localPath.exists()) { // 获得文件目录,判断目录是否存在,不存在就新建一个
localPath.mkdirs();
}
//存文件
for (MultipartFile f : file) {
String filename = f.getOriginalFilename();
String path = docPath +filename;
File filePath = new File(path);
BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(filePath));// 保存文件到目录下
out.write(f.getBytes());//在创建好的文件中写入f.getBytes()
out.flush();
out.close();
productOutsourceEntity.setFileUrl(path);
log.info("数据库中FileUrl储存"+productOutsourceEntity.getFileUrl());
}
productOutsourceMapping.insert(productOutsourceEntity);
return Constants.SUCCESSCODE;
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
req.setAttribute("error", "添加文件失败");
return Constants.FAILCODE;
}
}