在Spring中使用MultipartFile接收文件
/**
* 获取文件类型 .getContentType() image/jpeg
* 获取函数原始名称 .getOriginalFilename() 1640016160965.jpg
* 获取文件大小 .getSize() 14209
* 将文件保存到dest指定的位置 transferTo(File dest)
*/
import java.io.File;
import org.springframework.web.multipart.MultipartFile;
import cn.hutool.core.lang.UUID;
public class UploadTran {
private volatile static UploadTran fileTran;
public UploadTran() {
}
public static UploadTran getInstance() {
if (fileTran == null) {
synchronized (UploadTran.class) {
if (fileTran == null) {
fileTran = new UploadTran();
}
}
}
return fileTran;
}
public String transformatiom(MultipartFile file,String uploadPath) {
String fileName = file.getOriginalFilename();
String str = fileName.substring(fileName.lastIndexOf("."));
String newFile = UUID.randomUUID().toString() + str;
String path = uploadPath + newFile;
System.out.println(path);
File dest = new File(path);
if (!dest.getParentFile().exists()) {
dest.getParentFile().mkdirs();
}
try {
file.transferTo(dest);
} catch (Exception e) {
e.printStackTrace();
}
return newFile;
}
}
使用FTP上传文件 引入依赖
<!-- hutool工具包 -->
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.7.16</version>
</dependency>
<dependency>
<groupId>commons-net</groupId>
<artifactId>commons-net</artifactId>
<version>3.6</version>
</dependency>
package com.test.controller;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import cn.hutool.extra.ftp.Ftp;
import cn.hutool.core.io.FileUtil;
@RestController
public class FPTController {
@Value("${web.file-path}")
private String filePath;
@PostMapping("/FPTUpload")
public Object FPTUpload(@RequestParam("myFile") MultipartFile myFile) throws IOException {
Ftp ftp = new Ftp("localhost", 21, "ftp", "123");
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MMdd");
String newfilePath = sdf.format(new Date()) ;
String ftpPath ="/"+newfilePath;
String OriginalFilePath =filePath+myFile.getOriginalFilename();
ftp.upload(ftpPath, FileUtil.file(OriginalFilePath));
ftp.close();
return "ok";
}
}
在配置文件中: 测试:
|