您的位置:首页 > 编程语言 > Java开发

java文件上传下载

2017-08-11 17:19 309 查看

java文件上传下载

fileUtil

package com.zzq.utils;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.UUID;

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

import org.springframework.web.multipart.MultipartFile;

import com.zzgx.imake.pc.user.entity.Result;

/**
* 文件操作
* @author zzgx
*
*/
public class FileUtil {

/**
* 文件上传
* @param file
* @return
*/
public static Result uploadFile(HttpServletRequest request,MultipartFile file){
Properties urlPro = new Properties();
try {
urlPro.load(FileUtil.class.getResourceAsStream("/config/plateConfig.properties"));
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
String localPath = urlPro.getProperty("localPath");
String httpPath = urlPro.getProperty("httpPath");

Result result = new Result();
Map<String, Object> map = new HashMap<String, Object>();
String imageUrl = "";
String resourcePath = FileUtil.class.getResource("").getPath();
if (file != null && !file.isEmpty()) {
// 获得原始文件名
String fileName = file.getOriginalFilename();

//对文件名编码,以免中文名字出现问题
fileName = dealWithFileChineseName(fileName);

System.out.println("原始文件名:" + fileName);
// 新文件名(唯一)
String newFileName = UUID.randomUUID().toString()+"_"+fileName;
System.out.println("新文件名:" + newFileName);
//本地存储
String path = resourcePath.substring(0, resourcePath.lastIndexOf("WEB-INF")) + "static/image/"+new SimpleDateFormat("yyyy-MM-dd").format(new Date())+"/";
// 存储位置
//String path = localPath+new SimpleDateFormat("yyyy-MM-dd").format(new Date())+"/";

File f = new File(path);
BufferedInputStream bis = null;
BufferedOutputStream bs = null;
if (!f.exists())
f.mkdirs();
if (!file.isEmpty()) {
try {
bis = new BufferedInputStream(file.getInputStream());

e61a
bs = new BufferedOutputStream(new FileOutputStream(path + newFileName));
int b = 0;
while ((b = bis.read()) != -1) {
bs.write(b);
}
} catch (Exception e) {
e.printStackTrace();
}finally{
try {
if(bis != null){
bis.close();
bis = null;
}
if(bs != null){
bs.close();
bs = null;
}
} catch (IOException e) {
e.printStackTrace();
return result;
}
}
}
System.out.println("上传文件到:" + path + newFileName);

//本地使用的http路径
String contextPath = request.getContextPath();
String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
+ contextPath + "/static/image/";
imageUrl = basePath+new SimpleDateFormat("yyyy-MM-dd").format(new Date())+"/" + newFileName;
//imageUrl = httpPath+new SimpleDateFormat("yyyy-MM-dd").format(new Date())+"/" + newFileName;

System.out.println("文件相对路径:" + imageUrl);
} else {
result.setStatus(500);
result.setMessage("上传文件不能为空!!");
return result;
}
map.put("imageUrl", imageUrl);
result.setStatus(200);
result.setMessage("文件上传成功!");
result.setData(map);
return result;
}

/**
* 图片上传
* @param file
* @return
*/
public static Result uploadImg(HttpServletRequest request,MultipartFile file){
Properties urlPro = new Properties();
try {
urlPro.load(FileUtil.class.getResourceAsStream("/config/plateConfig.properties"));
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
String localPath = urlPro.getProperty("localPath");
String httpPath = urlPro.getProperty("httpPath");
Result result = new Result();
Map<String, Object> map = new HashMap<String, Object>();
String imageUrl = "";
String resourcePath = FileUtil.class.getResource("").getPath();
if (file != null && !file.isEmpty()) {
// 获得原始文件名
String fileName = file.getOriginalFilename();

//对文件名编码,以免中文名字出现问题
fileName = dealWithFileChineseName(fileName);

String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
if (suffix.equals("png") || suffix.equals("jpg") || suffix.equals("jpeg") || suffix.equals("PNG")
|| suffix.equals("JPG") || suffix.equals("JPEG")){
System.out.println("原始图片名:" + fileName);
// 新文件名(唯一)
String newFileName = UUID.randomUUID().toString()+"_"+fileName;
System.out.println("新图片名:" + newFileName);

//本地存储
String path = resourcePath.substring(0, resourcePath.lastIndexOf("WEB-INF")) + "static/image/"+new SimpleDateFormat("yyyy-MM-dd").format(new Date())+"/";
//服务器部署测试路径
//String path = localPath+new SimpleDateFormat("yyyy-MM-dd").format(new Date())+"/";
File f = new File(path);
BufferedInputStream bis = null;
BufferedOutputStream bs = null;
if (!f.exists())
f.mkdirs();
if (!file.isEmpty()) {
try {
bis = new BufferedInputStream(file.getInputStream());
bs = new BufferedOutputStream(new FileOutputStream(path + newFileName));
int b = 0;
while ((b = bis.read()) != -1) {
bs.write(b);
}
} catch (Exception e) {
e.printStackTrace();
}finally{
try {
if(bis != null){
bis.close();
bis = null;
}
if(bs != null){
bs.close();
bs = null;
}
} catch (IOException e) {
e.printStackTrace();
return result;
}
}
}
System.out.println("上传图片到:" + path + newFileName);

//本地使用的http路径
String contextPath = request.getContextPath();
String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
+ contextPath + "/static/image/";
imageUrl = basePath+new SimpleDateFormat("yyyy-MM-dd").format(new Date())+"/" + newFileName;
//服务器使用的http路径
//imageUrl = httpPath+new SimpleDateFormat("yyyy-MM-dd").format(new Date())+"/" + newFileName;
System.out.println("图片相对路径:" + imageUrl);
}else{
result.setStatus(500);
result.setMessage("图片格式不对!");
return result;
}
} else {
result.setStatus(500);
result.setMessage("上传图片不能为空!!");
return result;
}
map.put("imageUrl", imageUrl);
result.setStatus(200);
result.setMessage("图片上传成功!");
result.setData(map);
return result;
}

/**
* 文件下载
* @param path
* @param response
* @return
*/
public static void downloadFiles(String urlStr, HttpServletResponse response){
//要下载的文件
HttpURLConnection conn = null;

urlStr = TranEncodeTOGB(urlStr);

String fileName = urlStr.substring(urlStr.lastIndexOf("/")+1);//文件名

//对文件名解码
fileName = decodeHasEncodeFileName(fileName);
//拿掉uuid
fileName = fileName.substring(fileName.lastIndexOf("_")+1);
try {
fileName = new String(fileName.getBytes(), "ISO-8859-1");
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
}

//设置响应格式
response.reset();
response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
response.setContentType("application/octet-stream;charset=UTF-8");

BufferedInputStream bis = null;//定义输入流
BufferedOutputStream bos = null;//定义输出流
try {
URL url = new URL(urlStr);
conn = (HttpURLConnection)url.openConnection();
conn.connect();

bis = new BufferedInputStream(conn.getInputStream());
bos = new BufferedOutputStream(response.getOutputStream());
int b = 0;
while ((b = bis.read()) != -1) {
bos.write(b);
}

} catch (Exception e) {
e.printStackTrace();
} finally {
conn.disconnect();
try {
if(bis != null){
bis.close();
bis = null;
}
if(bos != null){
bos.close();
bos = null;
}
} catch (IOException e) {
e.printStackTrace();
}

}
}

//自动转码
public static String TranEncodeTOGB(String str) {
try {
String strEncode = getEncoding(str);
System.out.println(strEncode);
if("UTF-8".equals(strEncode)){return str;} //如果编码本来就是UTF-8,直接返回传入参数
String temp = new String(str.getBytes(strEncode), "UTF-8");
return temp;
} catch (java.io.IOException ex) {
return null;
}
}

//判断编码
public static String getEncoding(String str) {
String encode = "GB2312";
try {
if (str.equals(new String(str.getBytes(encode), encode))) {
String s = encode;
return s;
}
} catch (Exception exception) {
}
encode = "ISO-8859-1";
try {
if (str.equals(new String(str.getBytes(encode), encode))) {
String s1 = encode;
return s1;
}
} catch (Exception exception1) {
}
encode = "UTF-8";
try {
if (str.equals(new String(str.getBytes(encode), encode))) {
String s2 = encode;
return s2;
}
} catch (Exception exception2) {
}
encode = "GBK";
try {
if (str.equals(new String(str.getBytes(encode), encode))) {
String s3 = encode;
return s3;
}
} catch (Exception exception3) {
}
return "";
}

/**
* 上传文件时处理中文名字的文件
* 统一编码 并 将编码后的 %替换为=
* @param urlStr
* @return
*/
public static String dealWithFileChineseName(String fileName){
String newString = "";
try {
newString = URLEncoder.encode(fileName, "UTF-8");
newString = newString.replaceAll("%", "=");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return newString;
}

/**
* 文件下载时,对已编码的文件名解码
* @return
*/
public static String decodeHasEncodeFileName(String fileName){
String newString = "";
try {
newString = fileName.replaceAll("=", "%");
newString = URLDecoder.decode(newString, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return newString;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: