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. 解决Webpack 安装sass时出现的错误

    webpack环境下,加载css需要 css-loader 和 style-loader. css-loader:使用类似@import和url(...)的方法实现 require的功能: style ...

  2. String创建方式的区别

    String str0 = "abc"; String str1 = new String("abc"); 第一句执行后,会在String pool中创建一个& ...

  3. 查看linuxCPU信息

    linux 下查看机器是cpu是几核的 几个cpu more /proc/cpuinfo |grep "physical id"|uniq|wc -l 每个cpu是几核(假设cpu ...

  4. SpringBoot2.0整合Sharding-Jdbc

    maven: <parent> <groupId>org.springframework.boot</groupId> <artifactId>spri ...

  5. handle 机制的原理是什么

    作者:milter链接:https://www.zhihu.com/question/19703357/answer/107984017来源:知乎著作权归作者所有.商业转载请联系作者获得授权,非商业转 ...

  6. cors实现跨域(.net和jquery)

    本文引用自:http://blog.csdn.net/xuwei_xuwei/article/details/29845865 客户端 一个jquery cors请求例子: $.ajax({     ...

  7. 使用SpringMVC的crud操作时,进行数据修改,但是修改成功后,页面无法显示lastName属性值(被修改的那条记录)

    我这个错误的原因在于,把map的键写错了,它必须和类名第一个字母小写相同 @ModelAttribute public void getEmployee(@RequestParam(value=&qu ...

  8. DOM元素的位置、尺寸及更多的信息

    一.基本概念 document.documentElement是整个DOM树的根节点,对应的元素就是html.下面将其称作根元素或根节点. document.body,对应的元素是body 二.浏览器 ...

  9. javascript HTML DOM 简单介绍

    JavaScript HTML DOM通过 HTML DOM,可访问 JavaScript HTML 文档的所有元素.HTML DOM (文档对象模型)当网页被加载时,浏览器会创建页面的文档对象模型( ...

  10. Windows API的消息处理机制

    上个学期找实习失利,让我觉得自己基础打得不够牢固,所以在华为实习的这三个月里,每天下班都在复习理论课的知识,顺便刷了一个月的 LeetCode.本来以为找工作是势在必得了,结果这个学期秋季校招的坑爹经 ...