前言
jersey 框架:支持将文件上传到另一台的服务器上(tomcat为例))
这里是直接使用tomcat搭建的一个文件服务器,搭建过程就不多蝉诉了
代码
package com.bingdeng.demo.webapi.util;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.WebResource;
import com.bingdeng.demo.webapi.handler.GlobalRunTimeException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.ConnectException;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* 文件操作工具类
* Created by fh on 2018/1/11.
*/
public class FileUtil {
private static Logger log = LoggerFactory.getLogger(FileUtil.class);
//校验路径开头
private static final String PATTERN_REGEX = "^(http|https)://.+";
//文件上传服务器
private static String fileHost;
public static void setFileHost(String fileHost) {
FileUtil.fileHost = fileHost;
}
/**
* 存储文件
*
* @param file 文件
* @param path 文件存储路径(文件夹)
* @return
*/
public static String getUploadFileName(MultipartFile file, String path) {
if (path == null) {
log.error("保存文件路径为空");
return null;
}
String newFileUrl = null;
if (file != null) {
//获取内容类型
// String contentType = file.getContentType();
//获取文件名及类型
String fieldOriginalName = file.getOriginalFilename();
//获取文件后缀
String fieldType = fieldOriginalName.substring(fieldOriginalName.lastIndexOf(".") + 1);
//重新定义文件名
String tempNewName = getRandomFileName();
//保存图片服务器的请求路径
newFileUrl = path + tempNewName + "." + fieldType;
// long size = file.getSize();
try {
//若是文件服务器,走这里
if (verifyUrlByRegEx(path)) {
//实例化一个Jersey
Client client = new Client();
//设置请求路径
WebResource resource = client.resource(newFileUrl);
//发送post get put
resource.put(String.class, file.getBytes());
} else {
File dirPath = new File(path);
if (!dirPath.exists()) {
dirPath.mkdirs();
}
dirPath.setWritable(true, false);
file.transferTo(new File(newFileUrl));
File fieldIsExit = new File(newFileUrl);
if (!fieldIsExit.exists()) {
log.error("文件转存失败");
} else {
log.info("文件上传成功:url={}", newFileUrl);
}
newFileUrl = newFileUrl.replace(fileHost, "");
}
} catch (IOException e) {
log.error("文件上传失败,msg:{}", e.getMessage());
throw new GlobalRunTimeException(BondStatusCodeEnum.CODE_70004.getCode(), "文件上传失败", null);
}
}
return newFileUrl;
}
/**
* 存储文件
*
* @param fileBytes 文件
* @param nameSuffix 后缀名
* @param path 文件存储路径(文件夹)
* @return
*/
public static String getUploadFileName(byte[] fileBytes, String path, String nameSuffix) {
if (StrUtil.isEmpty(path) || StrUtil.isEmpty(nameSuffix)) {
log.error("文件路径或文件后缀名为空");
return null;
}
String newFileUrl = null;
if (fileBytes != null && fileBytes.length > 0) {
//重新定义文件名-当前时间:如2018-6-9-10-30-57-104000000.jpg
LocalDateTime today = LocalDateTime.now();
String tempNewName = getRandomFileName();
//保存图片服务器的请求路径
newFileUrl = path + tempNewName + "." + nameSuffix;
try {
//若是文件服务器,走这里
if (verifyUrlByRegEx(path)) {
//实例化一个Jersey
Client client = new Client();
//设置请求路径
WebResource resource = client.resource(newFileUrl);
//发送post get put
resource.put(String.class, fileBytes);
} else {
File dirPath = new File(path);
if (!dirPath.exists()) {
dirPath.mkdirs();
}
dirPath.setWritable(true, false);
File fieldIsExit = cn.hutool.core.io.FileUtil.writeBytes(fileBytes, newFileUrl);
if (!fieldIsExit.exists()) {
log.error("文件转存失败");
} else {
log.info("文件上传成功:url={}", newFileUrl);
}
newFileUrl = newFileUrl.replace(fileHost, "");
}
} catch (Exception e) {
log.error("文件上传失败,msg:{}", e.getMessage());
throw new GlobalRunTimeException(BondStatusCodeEnum.CODE_70004.getCode(), "文件上传失败", null);
}
}
return newFileUrl;
}
/**
* URL以http或者https开头返回true,否则返回false
*
* @param path
* @return
*/
public static boolean verifyUrlByRegEx(String path) {
Pattern pattern = Pattern.compile(PATTERN_REGEX);
Matcher matcher = pattern.matcher(path);
return matcher.matches();
}
/**
* 判断是否是支持的图片格式
*
* @param type
* @return
*/
public static boolean judgeImageType(String type) {
for (String imageType : ConstantUtil.IMAGETYPE_CONSTANT) {
if (imageType.equals(type.toLowerCase())) {
return true;
}
}
return false;
}
public static String getRandomFileName() {
return UUID.randomUUID().toString().replace("-","");
}
}