springboot以FTP方式上传文件到远程服务器
此处远程服务器是ubuntu,关于ftpserver的配置请参考该文https://blog.csdn.net/sunxiaoju/article/details/85224602,在此处就不再赘述。该篇文章主要针对如何实现代码来进行代码干货的分享。
本小编用的前台为layui框架。话不多说直接上干货,代码没什么好解释的,直接贴出前后台代码以供大家分享使用。
一、html代码
<div class=”layui-form-item”>
<label class=”layui-form-label”>上传附件:</label>
<div class=”layui-input-block doc-litpic”>
<button type=”button” name=”avatar” class=”layui-btn layui-btn-sm” data-url=”/admin/archives/upload.html” id=”larry-litpic”><i class=”layui-icon”></i>本地上传</button>
<a id=”upload-filename-display” style=”color: blue” href=””></a>
<div class=”larryms-img-view”>
</div>
</div>
</div>
二、js代码
upload.render({
accept: ‘file’,
elem: ‘#larry-litpic’,
url: interface_cms_article_upload,
field: ‘fileNames’,
done : function (res, index, upload) {
if(res.code != 200){
layer.open({
icon : 2,
skin : “layui-layer-molv”,
content : res.msg
});
}else{
layer.open({
icon : 1,
skin : “layui-layer-molv”,
content : res.msg
});
$(‘#upload-filename-display’).text(res.filename);
$(“input[name=’fileId’]”).val(res.filename);
}
},
error : function (res) {
}
});
三、后台controller:
@RequestMapping(value = “/upload”)
@ApiOperation(value = “本地文件上传”,notes =”本地文件上传” )
public Map uploadfunction(HttpServletRequest request, HttpServletResponse response){
//创建文件对象并获取请求中的文件对象
MultipartFile file = null;
Map resultData = new HashMap();
try{
MultipartHttpServletRequest mRequest = (MultipartHttpServletRequest) request;
file = mRequest.getFile(“fileNames”);
//判断上传非空
if(null == file) {
resultData.put(“code”,0);
resultData.put(“msg”,”上传文件失败”);
resultData.put(“filename”,file.getOriginalFilename());
return resultData;
}
//上传需要导入数据的文件
//用来检测程序运行时间
long startTime=System.currentTimeMillis();
System.out.println(“上传的文件名为:”+file.getOriginalFilename());
String fileName = file.getOriginalFilename();
InputStream inputStream = file.getInputStream();
String hostName = uploadUtil.getHostname();
String username = uploadUtil.getUsername();
String password = uploadUtil.getPassword();
String targetPath = uploadUtil.getTargetPath();
String suffix = cmsArticleService.getSuffix(fileName);
fileName = cmsArticleService.upload(hostName,username,password,targetPath,suffix,inputStream);
//计算上传时间
long endTime=System.currentTimeMillis();
String uploadTime = String.valueOf(endTime-startTime);
System.out.println(“上传所用时间:”+uploadTime+”ms”);
resultData.put(“code”,200);
resultData.put(“msg”,”上传文件成功”);
resultData.put(“filename”,fileName);
return resultData;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
四、后台service上传至远程服务器
//FTP文件上传
public static String upload(String hostname,String username,String password,
String targetPath,String suffix,InputStream inputStream) throws SocketException, IOException {
//实例化ftpClient
FTPClient ftpClient = new FTPClient();
//设置登陆超时时间,默认是20s
ftpClient.setDataTimeout(12000);
//1.连接服务器
ftpClient.connect(hostname,21);
//2.登录(指定用户名和密码)
boolean b = ftpClient.login(username,password);
if(!b) {
System.out.println(“登陸超時”);
if (ftpClient.isConnected()) {
// 断开连接
ftpClient.disconnect();
}
}
// 设置字符编码
ftpClient.setControlEncoding(“UTF-8″);
//基本路径,一定存在
String basePath=”/”;
String[] pathArray = targetPath.split(“/”);
for(String path:pathArray){
basePath+=path+”/”;
//3.指定目录 返回布尔类型 true表示该目录存在
boolean dirExsists = ftpClient.changeWorkingDirectory(basePath);
//4.如果指定的目录不存在,则创建目录
if(!dirExsists){
//此方式,每次,只能创建一级目录
boolean flag=ftpClient.makeDirectory(basePath);
if (flag){
System.out.println(“创建成功!”);
}
}
}
//重新指定上传文件的路径
ftpClient.changeWorkingDirectory(targetPath);
//5.设置上传文件的方式
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
//使用uuid,保存文件名唯一性
String uuid= UUID.randomUUID().toString();
/**
* 6.执行上传
* remote 上传服务后,文件的名称
* local 文件输入流
* 上传文件时,如果已经存在同名文件,会被覆盖
*/
boolean uploadFlag = ftpClient.storeFile(uuid+suffix,inputStream);
if(uploadFlag)
System.out.println(“上传成功!”);
return uuid+suffix;
}
五、获取yml配置的工具类
@Data
@Component
public class UploadUtil {
@Value(“${upload.hostname}”)
private String hostname;
@Value(“${upload.username}”)
private String username;
@Value(“${upload.password}”)
private String password;
@Value(“${upload.targetPath}”)
private String targetPath;
}