package koi.api.server.controllers.test;
import lombok.extern.slf4j.Slf4j;
import monkey.common.Result;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
@Service
@Slf4j
public class UploadAnddownload {
//以文件流的方式
public Result uploadFile(MultipartFile multiFile,HttpServletRequest request){
// 获取项目部署路径
/* String appPath = request.getServletContext().getRealPath("/");
// 构建上传文件的目录路径
String path = appPath + "static/upload/";*/
//绝对路劲
// String path = "C:\Users\鲜庆龙\Desktop\fsdownload";
//相对路径
String path = "src/main/resources/";
String fileName = "测试文件上传";
//构建文件对象
File file = new File(path);
//文件目录不存在则递归创建目录
if (!file.exists()) {
boolean mkdirs = file.mkdirs();
if (!mkdirs) {
log.error("创建文件夹异常");
return Result.success();
}
}
try {
//获取文件输入流
InputStream inputStream = multiFile.getInputStream();
//构建文件输出流
FileOutputStream outputStream = new FileOutputStream(fileName);
int copy = FileCopyUtils.copy(inputStream, outputStream);
log.info("上传成功,文件大小:{}", copy);
return Result.success();
} catch (IOException e) {
log.error("文件上传异常", e);
e.printStackTrace();
}
return Result.success();
}
public static boolean downloadToServer(String downloadUrl, String downloadPath, String downloadFileName) {
FileOutputStream fos = null;
BufferedInputStream bis = null;
boolean flag = false;
try {
URL url = new URL(downloadUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.connect();
bis = new BufferedInputStream(connection.getInputStream());
File file = new File(downloadPath);
if (!file.exists()) {
boolean mkdirs = file.mkdirs();
if (!mkdirs) {
log.error("创建文件目录失败");
return false;
}
}
String filePathName = downloadPath + File.separator + downloadFileName;
byte[] buf = new byte[1024];
int size;
fos = new FileOutputStream(filePathName);
while ((size = bis.read(buf)) != -1) {
fos.write(buf, 0, size);
}
flag = true;
log.info("文件下载成功,文件路径[" + filePathName + "]");
flag = true;
} catch (Exception e) {
log.error("下载文件异常", e);
} finally {
try {
if (bis != null) {
bis.close();
}
if (fos != null) {
fos.close();
}
} catch (IOException e) {
log.error("关流异常", e);
e.printStackTrace();
}
}
return flag;
}
}