package com.beisun.mbp.util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.nio.channels.FileChannel;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.util.FileCopyUtils;
import org.springframework.web.multipart.MultipartFile;

public class FileUtil {

/**
* 上传文件
* @param filePath 上传文件目录
* @param fileName 保存的文件名称
* @param file 文件流类
* @param request 请求
* @throws IOException IO异常
*/
public static void updoadFile(String filePath,String fileName, MultipartFile file,
HttpServletRequest request) throws IOException{
//如果文件夹不存在,则创建文件夹
File dirPath = new File(filePath);
if(!dirPath.exists()){
dirPath.mkdir();
}

File uploadFile = new File(dirPath +"/"+ fileName);
FileCopyUtils.copy(file.getBytes(), uploadFile);
}

/**
* 复制文件
* @param localFileName 原文件地址和文件名
* @param tmpFileName 目标文件地址和文件名
* @throws IOException
*/
public static void copyFile(String localFileName,String tmpFilePath,String tmpFileName) throws IOException{
File localFile = new File(localFileName);
File tmpFile = new File(tmpFilePath,tmpFileName);
FileCopyUtils.copy(localFile, tmpFile);
}

/**
* 删除文件
* @param fileName 文件地址和文件名
* @throws IOException
*/
public static void deleteFile(String fileName) throws IOException{
File localFile = new File(fileName);
localFile.delete();
}

/**
* 下载文件,是向页面输出流,不返回流
* @param filePath 文件服务器存储目录
* @param downloadName 下载文件保存的文件名
* @param fileName 服务器存储文件名
* @param request
* @param response
* @throws UnsupportedEncodingException
*/
@SuppressWarnings("static-access")
public static void downloadFile(String filePath,String downloadName,String fileName,HttpServletRequest request,HttpServletResponse response) throws UnsupportedEncodingException{

fileName = new java.net.URLDecoder().decode(fileName, "utf-8");
downloadName = new java.net.URLDecoder().decode(downloadName, "utf-8");
String path = filePath+fileName;

response.setContentType("application/octet-stream;charset=UTF-8");
response.setHeader("Content-Disposition", "attachment;filename=" + new String((downloadName).getBytes("GBK"), "iso8859-1"));
try {
//以流的形式下载文件
InputStream fis = new BufferedInputStream(new FileInputStream(path));
byte[] buffer = new byte[fis.available()];
fis.read(buffer);
fis.close();

OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
toClient.write(buffer);
toClient.flush();
toClient.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

/**
* 获取文件的is
* @param filePath 文件服务器存储目录
* @param fileName 服务器存储文件名
* @param request
* @param response
* @throws UnsupportedEncodingException
*/
@SuppressWarnings("static-access")
public static InputStream getFileIS(String filePath,String fileName,HttpServletRequest request,HttpServletResponse response) throws UnsupportedEncodingException{

fileName = new java.net.URLDecoder().decode(fileName, "utf-8");
String path = filePath+fileName;
InputStream fis = null;
try {
//以流的形式下载文件
fis = new BufferedInputStream(new FileInputStream(path));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return fis;
}

/**
* 保存文件
* @param datas 文件数据
* @param pathName 文件路径
*/
public static void saveFile(byte[] datas,String pathName){
File file = new File(pathName);

//寤虹珛杈撳嚭瀛楄妭娴�
FileOutputStream fos;
try {
fos = new FileOutputStream(file);
//鐢‵ileOutputStream 鐨剋rite鏂规硶鍐欏叆瀛楄妭鏁扮粍
fos.write(datas);
//涓轰簡鑺傜渷IO娴佺殑寮�攢锛岄渶瑕佸叧闂�
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 获取文件数据
* @param pathName 文件路径
* @return
*/
public static byte[] getFile(String pathName){
File file = new File(pathName);
byte[] buffer = null;
try {
FileInputStream fis = new FileInputStream(file);
ByteArrayOutputStream bos = new ByteArrayOutputStream(1000);
byte[] b = new byte[1000];
int n;
while ((n = fis.read(b)) != -1) {
bos.write(b, 0, n);
}
fis.close();
bos.close();
buffer = bos.toByteArray();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return buffer;

}

/**
* 计算文件大小文件大小
* @param filePath 文件路径例如:E:\\imgData\\afr\\9211496189393485.jpg
* @return 文件大小 Kb
*/
public static long GetFileSize(String filePath){
long fileSize=0l;
FileChannel fc= null;
try {
File f= new File(filePath);
if (f.exists() && f.isFile()){
FileInputStream fis= new FileInputStream(f);
fc= fis.getChannel();
fileSize=fc.size()/1024;
//logger.info(fileSize);
}else{
//logger.info("file doesn't exist or is not a file");
}
} catch (FileNotFoundException e) {
//logger.error(e);
} catch (IOException e) {
//logger.error(e);
} finally {
if (null!=fc){
try{
fc.close();
}catch(IOException e){
//logger.error(e);
}
}
}

return fileSize;
}

/**
* getImage 根据图片的路径获取图片给前台
* @author sunjianbo
* @time 2016年8月25日上午10:41:37
* @param response
* @param request
* @param filePath
* @throws Exception
*/
//@RequestMapping(value = "/getImage.do", method = RequestMethod.GET)
public void getImage(HttpServletResponse response, HttpServletRequest request,String filePath)
throws Exception {

BufferedOutputStream bos = null;
try {
bos = new BufferedOutputStream(response.getOutputStream());

byte[] data = getFile(filePath);
bos.write(data);
bos.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (bos != null)
bos.close();
}
}

}

fileUtil文件的上传下载的更多相关文章

  1. Spring实现文件的上传下载

    背景:之前一直做的是数据库的增删改查工作,对于文件的上传下载比较排斥,今天研究了下具体的实现,发现其实是很简单.此处不仅要实现单文件的上传,还要实现多文件的上传. 单文件的下载知道了,多文件的下载呢? ...

  2. 在Window的IIS中创建FTP的Site并用C#进行文件的上传下载

    文件传输协议 (FTP) 是一个标准协议,可用来通过 Internet 将文件从一台计算机移到另一台计算机. 这些文件存储在运行 FTP 服务器软件的服务器计算机上. 然后,远程计算机可以使用 FTP ...

  3. 创建FTP的Site并用C#进行文件的上传下载

    创建FTP的Site并用C#进行文件的上传下载 文件传输协议 (FTP) 是一个标准协议,可用来通过 Internet 将文件从一台计算机移到另一台计算机. 这些文件存储在运行 FTP 服务器软件的服 ...

  4. linux链接及文件互相上传下载

    若排版紊乱可查看我的个人博客原文地址 基本操作 本篇博客主要介绍如何去链接远程的linux主机及如何实现本地与远程主机之间文件的上传下载操作,下面的linux系统是CentOS6.6 链接远程linu ...

  5. SocketIo+SpringMvc实现文件的上传下载

    SocketIo+SpringMvc实现文件的上传下载 socketIo不仅可以用来做聊天工具,也可以实现局域网(当然你如果有外网也可用外网)内实现文件的上传和下载,下面是代码的效果演示: GIT地址 ...

  6. JAVAWEB之文件的上传下载

    文件上传下载 文件上传: 本篇文章使用的文件上传的例子使用的都是原生技术,servelt+jdbc+fileupload插件,这也是笔者的习惯,当接触到某些从未接触过的东西时,总是喜欢用最原始的东西将 ...

  7. SSM框架之中如何进行文件的上传下载

    SSM框架的整合请看我之前的博客:http://www.cnblogs.com/1314wamm/p/6834266.html 现在我们先看如何编写文件的上传下载:你先看你的pom.xml中是否有文件 ...

  8. python使用ftplib模块实现FTP文件的上传下载

    python已经默认安装了ftplib模块,用其中的FTP类可以实现FTP文件的上传下载 FTP文件上传下载 # coding:utf8 from ftplib import FTP def uplo ...

  9. php文件夹上传下载控件分享

    用过浏览器的开发人员都对大文件上传与下载比较困扰,之前遇到了一个php文件夹上传下载的问题,无奈之下自己开发了一套文件上传控件,在这里分享一下.希望能对你有所帮助. 以下是实例的部分脚本文件 这里我先 ...

随机推荐

  1. vue-scroller的使用

    一 安装 使用npm 安装 npm install vue-scroller -S 二 引入 https://www.jianshu.com/p/a39f5276ff0b https://www.np ...

  2. CSS3:布局display属性的flex(弹性布局)

    CSS3:布局display属性的flex(弹性布局) 一.简介 Flex是Flexible Box的缩写,意为"弹性布局",用来为盒状模型提供最大的灵活性.设为Flex布局以后, ...

  3. spring boot应用测试框架介绍

    一.spring boot应用测试存在的问题 官方提供的测试框架spring-boot-test-starter,虽然提供了很多功能(junit.spring test.assertj.hamcres ...

  4. CVE补丁安全漏洞【学习笔记】

    更新安卓系统的CVE补丁网站:https://www.cvedetails.com/vulnerability-list/vendor_id-1224/product_id-19997/version ...

  5. [BZOJ1257]余数之和

    Description 给出正整数n和k,计算j(n, k)=k mod 1 + k mod 2 + k mod 3 + … + k mod n的值 其中k mod i表示k除以i的余数. 例如j(5 ...

  6. C3p0的参数

    C3p0的参数设置:ComboPooledDataSource和BasicDataSource一样提供了一个用于关闭数据源的close()方法,这样我们就可以保证Spring容器关闭时数据源能够成功释 ...

  7. Mysql 常用单词

    单词: CRUD:增删改查(create/read/update/delete) create:新增项目 read:查询 update:修改 delete:删除 desc 表名:查看表结构 drop: ...

  8. Linux.Siggen.180

    from: https://vms.drweb.com/virus/?i=15455134&lng=en Linux.Siggen.180 Added to Dr.Web virus data ...

  9. MySql 存储过程实例 - 转载

    MySql 存储过程实例 将下面的语句复制粘贴可以一次性执行完,我已经测试过,没有问题! MySql存储过程简单实例:                                          ...

  10. ElasticSearch性能优化

    一.搜索效率优化 批量提交 当有大量数据提交的时候,建议采用批量提交. 比如在做 ELK 过程中 ,Logstash indexer 提交数据到 Elasticsearch 中 ,batch size ...