上传文件到linux服务器
@RestController
public class UploadController {
@Value("${file.path}")
private String filePath;
@PostMapping("/uploadFile")
public Map<String, Object> uploadFile(@RequestParam("file") MultipartFile file){
Map<String, Object> map = new HashMap<String, Object>();
if (file.getOriginalFilename() == null){
map.put("code",500);
map.put("message","文件名为空!");
return map;
}
try {
File file1 = new File(filePath, file.getOriginalFilename());
//如果目标文件夹不存在就创建
if (!file1.exists()){
file1.createNewFile();
}
file.transferTo(file1);
}catch (Exception e){
map.put("code",500);
map.put("message","文件服务器上传失败!");
return map;
}
map.put("code",200);
map.put("message","文件服务器上传成功!");
return map;
}
}
多文件上传
@Value("${file.upload.path}")
private String fileUploadPath;
@PostMapping("/file")
public R uploadFile(@RequestParam("files") MultipartFile[] multipartFiles) throws IOException {
String parentFile = fileUploadPath;//服务器保存图片的路径
//如果父文件夹不存在,就创建
File parent = new File(parentFile);
if (!parent.getParentFile().exists()) {
parent.mkdirs();
}
if(multipartFiles == null){
return R.error("文件为空");
}
for (MultipartFile file : multipartFiles) {
String filename = file.getOriginalFilename(); //获取上传图片的文件名,包含后缀
String suffixName = filename.substring(filename.lastIndexOf("."));//图片后缀
String randomFileName = RandomStringUtils.random(6, true, true);//生成6个字符的随机串
String nowName = randomFileName + suffixName;//最后保存在服务器时的文件名
File file1 = new File(parent, nowName);
//将图片保存入服务器
file.transferTo(file1);
}
return R.ok("图片上传成功");
}
跨服务器上传文件
例如我有一个专门存储文件的服务器,我所有的项目都需要将文件存储到文件服务器上。当我们有多个服务器的时候就可以这样将所有服务的文件上传到我们规定的文件服务器中
例如:访问本地的项目(localhost)将文件上传到linux服务器上
将上个demo继续在服务器上运行,然后我们本地的服务去调用刚才那个部署在服务器上的项目的上传文件的接口
思路:访问一个服务器上的上传文件的接口,然后这个接口的方法再调用post请求去访问文件服务器上的上传文件的接口就行
server:
port: 8080
upload:
path: http://你的文件服务器地址:9080/uploadFile
@RestController
public class UploadFileController {
@Value("${upload.path}")
private String uploadPath;
@PostMapping("/upload")
public String upload(@RequestParam("file") MultipartFile file) throws IOException {
//文件为空
if (file.isEmpty()){
return "文件异常";
}
CloseableHttpClient client = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(uploadPath);
HttpEntity httpEntity = MultipartEntityBuilder.create()
.addBinaryBody("file", file.getBytes(), ContentType.MULTIPART_FORM_DATA, file.getOriginalFilename())
.build();
httpPost.setEntity(httpEntity);
HttpResponse response = client.execute(httpPost);
int statusCode = response.getStatusLine().getStatusCode();
System.out.println(statusCode);
return file.getOriginalFilename();
}
}