Java 实现文件上传到服务器
接口
/**
* 文件上传
* @param request
* @param multiFile
* @return
*/
@ResponseBody
@RequestMapping(value = "/uploadToServer")
public AjaxResult uploadToServer(HttpServletRequest request, @RequestParam(value = "file", required = false) MultipartFile multiFile) {
try {
Pair<Boolean, String> pair = checkFile(multiFile);
if (!pair.getLeft()) {
return AjaxResult.error(pair.getRight());
}
Long temp = System.currentTimeMillis();
String fileName = multiFile.getOriginalFilename();
assert fileName != null;
String[] fileNames = fileName.split("\\.");
fileName = fileNames[0]+ temp.toString()+"."+fileNames[fileNames.length - 1];
boolean b = FileUploadUtil.uploadToServer(multiFile, appProperties.getUploadPath(), fileName);
return AjaxResult.success("上传成功!", fileName);
}
return AjaxResult.error("上传失败!");
} catch (Exception e) {
log.error("系统异常e:", e);
return AjaxResult.error("上传失败!");
}
}
里面使用的FileUploadUtil工具类
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.FileCopyUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
/**
* 文件上传工具类
* @author
* @date 2024年03月28日 9:27
*/
@Slf4j
public class FileUploadUtil {
/**
* 上传文件
*
* @param multiFile 文件
* @param uploadPath 服务器上要存储文件的路径
* @param uploadFileName 服务器上要存储的文件的名称
* @return
*/
public static boolean uploadToServer(MultipartFile multiFile, String uploadPath, String uploadFileName) {
//构建文件对象
File file = new File(uploadPath);
//文件目录不存在则递归创建目录
if (!file.exists()) {
boolean mkdirs = file.mkdirs();
if (!mkdirs) {
log.error("创建文件夹异常");
return false;
}
}
InputStream ins = null;
FileOutputStream outs = null;
try {
//获取文件输入流
ins = multiFile.getInputStream();
//构建文件输出流
outs = new FileOutputStream(uploadPath + uploadFileName);
int len;
byte[] bytes = new byte[1024];
//读取一个bytes的文件内容
while ((len = ins.read(bytes)) != -1) {
outs.write(bytes, 0, len);
}
outs.close();
log.info("上传成功:{}", uploadPath + uploadFileName);
return true;
} catch (IOException e) {
log.error("文件上传异常");
e.printStackTrace();
} finally {
try {
if (outs != null) {
outs.close();
}
if (ins != null) {
ins.close();
}
} catch (IOException e) {
log.error("关闭流异常");
e.printStackTrace();
}
}
return false;
}
/**
* 新文件上传
*
* @param multiFile 文件
* @param uploadPath 服务器上要存储文件的路径
* @param uploadFileName 服务器上要存储的文件的名称
* @return
*/
public static boolean newUploadToServer(MultipartFile multiFile, String uploadPath, String uploadFileName) {
//构建文件对象
File file = new File(uploadPath);
//文件目录不存在则递归创建目录
if (!file.exists()) {
boolean mkdirs = file.mkdirs();
if (!mkdirs) {
log.error("创建文件夹异常");
return false;
}
}
try {
//获取文件输入流
InputStream inputStream = multiFile.getInputStream();
//构建文件输出流
FileOutputStream outputStream = new FileOutputStream(uploadPath + uploadFileName);
int copy = FileCopyUtils.copy(inputStream, outputStream);
log.info("上传成功,文件大小:{}", copy);
return true;
} catch (IOException e) {
log.error("文件上传异常", e);
e.printStackTrace();
}
return false;
}
/**
* 拷贝文件信息
* @param resourceFile
* @param filename
* @return
*/
public static boolean copyFile(String resourceFile, String filename) {
// 源文件路径
if (StringUtils.isEmpty(resourceFile)) {
log.error("文件拷贝失败!缺少资源文件路径!");
return false;
}
if (StringUtils.isEmpty(filename)) {
log.error("文件拷贝失败!缺少文件名称!");
return false;
}
Path sourcePath = Paths.get(resourceFile);
try {
// 目标文件路径
File directory = new File("");
String targetPathStr = directory.getCanonicalPath().replace("\\", "/");
targetPathStr = targetPathStr + "/target/classes/static/lib/file/" + filename;
Path targetPath = Paths.get(targetPathStr);
// 执行文件拷贝
Files.copy(sourcePath, targetPath, StandardCopyOption.REPLACE_EXISTING);
log.info("文件拷贝成功!");
return true;
} catch (IOException e) {
log.error("文件拷贝失败:" + e.getMessage());
return false;
}
}
}