客户端
public static void main(String[] args) {
if(args.length<2){
LOGGER.info("启动参数缺失");
System.out.println("启动参数缺失");
}
String sourceBaseUrl = args[0];
String remoteBaseUrl = args[1];
try {
WatchKey watchKey;
// 监听文件夹下文件的新增
WatchService watchService = FileSystems.getDefault().newWatchService();
Paths.get(sourceBaseUrl).register(watchService, StandardWatchEventKinds.ENTRY_CREATE);
while (true) {
LOGGER.debug("等待文件加载...");
watchKey = watchService.take();//没有文件增加时,阻塞在这里
for (WatchEvent<?> event : watchKey.pollEvents()) {
String fileName = sourceBaseUrl + "\\" + event.context();
Path path = Paths.get(fileName);
File uploadFile = path.toFile();
uploadFile(uploadFile,remoteBaseUrl);//上传服务器
Files.deleteIfExists(path);
}
if (!watchKey.reset()) {
break; //中断循环
}
}
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
}
private static void uploadFile(File uploadFile,String url) {
MultipartPostMethod postMethod = new MultipartPostMethod(url);
try {
postMethod.addParameter("file",uploadFile);
postMethod.addParameter("fileName",uploadFile.getName());
HttpClient client = new HttpClient();
// 由于要上传的文件可能比较大 , 因此在此设置最大的连接超时时间
client.setConnectionTimeout(50000);
int status = client.executeMethod(postMethod);
if (status == HttpStatus.SC_OK) {
LOGGER.debug("上传成功");
} else {
LOGGER.error("上传失败");
}
} catch (Exception e) {
LOGGER.error("上传失败,原因:{}",e);
} finally {
// 释放连接
postMethod.releaseConnection();
}
}
服务端
@SpringBootApplication
@RestController
@Log4j2
public class FileStoreApplication {
private static String fileLocation;
public static void main(String[] args) {
if (args.length < 1) {
log.error("请输入文件存放路径");
return;
}
fileLocation = args[0];
SpringApplication.run(FileStoreApplication.class, args);
}
@PostMapping("")
public HttpServletResponse upload(@RequestParam("file") MultipartFile file,
@RequestParam("fileName")String fileName,
HttpServletResponse response) throws IOException {
if (StringUtils.isBlank(fileLocation)) {
response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
return response;
}
// io 写入
Path path = Paths.get(fileLocation,fileName);
Files.write(path, file.getBytes(), StandardOpenOption.CREATE);
log.info("上传成功");
return response;
}
}
原文:https://www.cnblogs.com/neverendingDreaming/p/14336759.html