package com.speed.common.file;
import com.alibaba.cola.dto.SingleResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;
import java.io.*;
import java.net.*;
import java.nio.charset.StandardCharsets;
/**
* 文件上传工具类
*
* @author plankton
* @date 2021/7/12 11:23
*/
public class FileUtils {
/**
* 文件上传地址(pc-Windows)主文件夹(默认)
*/
public static final String FOLDER_WINDOWS = "E:/file/";
/**
* 文件上传地址(pc-linux)主文件夹
*/
public static final String FOLDER_LINUX = "/data/file/";
/**
* 图片文件夹名 filetype=1
*/
public static final String IMAGE = "image";
/**
* 文档 filetype=2
*/
private static final String OFFICE = "office";
/**
* 视频 filetype=3
*/
private static final String VIDEO = "video";
/**
* 音乐 filetype=4
*/
private static final String MUSIC = "music";
/**
* 其他 filetype=5
*/
private static final String OTHER = "other";
private static Logger log = LoggerFactory.getLogger(FileUtils.class);
/**
* 超时时间
*/
private static final int TIME_OUT = 100 * 1000;
/**
* 边界标识 随机生成
*/
private static final String BOUNDARY = "letv";
private static final String PREFIX = "--";
private static final String LINE_END = "\r\n";
/**
* 内容类型
*/
private static final String CONTENT_TYPE = "multipart/form-data";
/**
* 上传文件到服务器
*
* @param file 需要上传的文件
* @param fileName 自定义上传文件的名称
* @param requestURL 文件服务器的url
* @return 返回响应的内容
*/
public static String upload(File file, String fileName, String requestURL) throws IOException {
log.info("FileUtils upload start, fileName : {}, url : {}", file.getName(), requestURL);
String result = null;
URL testUrl = new URL(requestURL);
HttpURLConnection urlConnection = (HttpURLConnection) testUrl.openConnection();
try {
urlConnection.connect();
} catch (IOException e) {
throw new ConnectException(e.getMessage());
} finally {
urlConnection.disconnect();
}
URL url = new URL(requestURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
try {
conn.setReadTimeout(TIME_OUT);
conn.setConnectTimeout(TIME_OUT);
// 允许输入流
conn.setDoInput(true);
// 允许输出流
conn.setDoOutput(true);
// 不允许使用缓存
conn.setUseCaches(false);
// 请求方式
conn.setRequestMethod("POST");
// 设置编码
conn.setRequestProperty("Charset", StandardCharsets.UTF_8.name());
conn.setRequestProperty("connection", "keep-alive");
conn.setRequestProperty("Content-Type", CONTENT_TYPE + ";boundary=" + BOUNDARY);
if (file != null) {
/*
* 当文件不为空,把文件包装并且上传
*/
DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
StringBuffer sb = new StringBuffer();
sb.append(PREFIX);
sb.append(BOUNDARY);
sb.append(LINE_END);
/*
* 这里重点注意: name里面的值为服务器端需要key 只有这个key 才可以得到对应的文件
* filename是文件的名字,包含后缀名的 比如:abc.png
*/
// 有传名称时用名称,未传名称时直接获取文件名
String name = fileName == null || "".equals(fileName) ? file.getName() : fileName;
log.info("FileUtils upload file name: {}", name);
sb.append("Content-Disposition: form-data; name=\"file\"; filename=\"" + name + "\"" + LINE_END);
sb.append("Content-Type: application/ctet-stream" + LINE_END);
sb.append(LINE_END);
/*
* 这里getBytes("UTF-8")是关键,否则传到服务端文件名会乱码,
* 若是在file.getName()处编码,则需要在服务端进行解码,
* 为了服务端的接口前后端共用,不再在服务端处理编码
*/
dos.write(sb.toString().getBytes(StandardCharsets.UTF_8.name()));
InputStream is = new FileInputStream(file);
byte[] bytes = new byte[1024 * 1024];
int len = 0;
while ((len = is.read(bytes)) != -1) {
dos.write(bytes, 0, len);
}
is.close();
dos.write(LINE_END.getBytes());
byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINE_END).getBytes();
dos.write(end_data);
dos.flush();
InputStream input = conn.getInputStream();
StringBuffer sb1 = new StringBuffer();
int ss;
while ((ss = input.read()) != -1) {
sb1.append((char) ss);
}
result = sb1.toString();
result = new String(result.getBytes(StandardCharsets.ISO_8859_1.name()), StandardCharsets.UTF_8.name());
}
} catch (MalformedURLException e) {
log.error("FileUtils upload MalformedURLException msg : {}", e.getMessage());
e.printStackTrace();
return null;
} catch (IOException e) {
log.error("FileUtils upload IOException msg : {}", e.getMessage());
e.printStackTrace();
return null;
} finally {
conn.disconnect();
}
log.info("FileUtils upload end, result : {}", result);
return result;
}
/**
* 有时候是MultipartFile,可以通过这个方法把MultipartFile.getInputStream()转成File
*/
public static void inputStreamToFile(InputStream ins, File file) {
try {
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
OutputStream os = new FileOutputStream(file);
int bytesRead = 0;
byte[] buffer = new byte[8192];
while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
os.write(buffer, 0, bytesRead);
}
os.close();
ins.close();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 文件上传工具
*
* @param file 源文件
* @return
*/
public static SingleResponse<FileEntity> uploadFile(MultipartFile file) {
log.info("uploadFile start, OriginalFilename:" + file.getOriginalFilename());
FileEntity fileEntity = new FileEntity();
// 目标文件路径
String filePath = FOLDER_LINUX + IMAGE + "/";
File targetFile = new File(filePath);
String fileName = file.getOriginalFilename();
String newFileName = System.currentTimeMillis() + fileName.substring(fileName.lastIndexOf("."));
if (!targetFile.exists()) {
targetFile.mkdirs();
}
try {
FileOutputStream fileOutputStream = new FileOutputStream(filePath + newFileName);
// 上传
fileOutputStream.write(file.getBytes());
fileOutputStream.flush();
fileOutputStream.close();
fileEntity.setFileID(System.currentTimeMillis());
fileEntity.setFileName(newFileName);
fileEntity.setFilePath(targetFile.getAbsolutePath());
} catch (FileNotFoundException FNF) {
log.error(FNF.getMessage());
return SingleResponse.buildFailure("500", FNF.getMessage());
} catch (IOException IO) {
log.error(IO.getMessage());
return SingleResponse.buildFailure("500", IO.getMessage());
} catch (NullPointerException NPE) {
log.error(NPE.getMessage());
return SingleResponse.buildFailure("500", NPE.getMessage());
}
return SingleResponse.of(fileEntity);
}
}
图片和文件上传到linux及本地
最新推荐文章于 2024-05-05 17:10:13 发布