在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;
/**
* 處理檔案或者圖片資訊 getInstance方法 實體化物件
*
* @author Windows
*
*/
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 ftp = new Ftp("localhost", 21, "ftp", "123");
//規劃路徑
// 規劃檔案存放的路徑
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MMdd");
String newfilePath = sdf.format(new Date()) ;
//ftp目錄
String ftpPath ="/"+newfilePath;
//源檔案目錄
String OriginalFilePath =filePath+myFile.getOriginalFilename();
// 上傳本地檔案
ftp.upload(ftpPath, FileUtil.file(OriginalFilePath));
// 關閉連接
ftp.close();
return "ok";
}
}
在組態檔中:

測驗:

轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/395439.html
標籤:其他
上一篇:AOP初識及實踐
下一篇:java球形【sphere】定義
