1搭建環(huán)境
IDEA+ windows10
image.png
2HTML頁面
upload.html
<!DOCTYPE html>
<html xmlns: th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="/app/upload" method="post" enctype="multipart/form-data">
選擇文件 <input type="file" name="uploadFile"/><br/>
<input type="submit" name="上傳"/><br/>
</form>
</body>
</html>
success.html
<!DOCTYPE html>
<html xmlns: th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>上傳成功</title>
</head>
<body>
文件上傳成功哨坪!
<button onclick="window.location.href = '/upload.html'">繼續(xù)添加</button>
</body>
</html>
wrong.html
<!DOCTYPE html>
<html xmlns: th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>錯誤</title>
</head>
<body>
文件上傳失敗!
<button onclick="window.location.href = '/upload.html'">繼續(xù)添加</button>
</body>
</html>
3 Controller 獲取html上傳的multipartfile
controller 接受html傳來的文件后 先將該文件存放在本地tomcat某目錄下(具體可以自行打印文件的路徑查看)猜拾。
然后讀取本地文件的路徑和文件名(文件名經(jīng)過了sha256加密) 新建輸入流
調(diào)用FTPUtil的上傳接口 上傳 到服務(wù)器上同時刪除本地的緩存文件
上傳成功則跳轉(zhuǎn)success界面可繼續(xù)添加
否則進入wrong界面
ps:本例中只針對ipa 和mount文件進行上傳
package com.example.demo.controller;
import com.example.demo.util.FTPUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.security.MessageDigest;
import java.text.SimpleDateFormat;
import java.util.Date;
@Controller
@RequestMapping("/app/")
public class UploadController {
@Value("${upload.host}")
private String host;
@Value("${upload.port}")
private int port;
@Value("${upload.userName}")
private String userName;
@Value("${upload.password}")
private String password;
@Value("${upload.basePath}")
private String basePath = "/";
private String filePath;
@RequestMapping("upload")
public String upload(MultipartFile uploadFile, HttpServletRequest req){
SimpleDateFormat sd = new SimpleDateFormat("yyyy/MM/dd");
String realPath = req.getSession().getServletContext().getRealPath("/uploadFile");
String format = sd.format(new Date());
File file = new File(realPath + format);
if (!file.isDirectory()){
file.mkdirs();
}
String oldName = uploadFile.getOriginalFilename();
MessageDigest messageDigest;
try{
messageDigest = MessageDigest.getInstance("SHA-256");
messageDigest.update(oldName.substring(0, oldName.indexOf(".")).getBytes());
String newName = byte2Hex(messageDigest.digest()) + oldName.substring(oldName.indexOf("."));
File storeFile = new File(file, newName);
uploadFile.transferTo(storeFile);
InputStream in = new FileInputStream(storeFile);
String prefix = oldName.substring(oldName.indexOf("."), oldName.length());
if(prefix.equals(".ipa")){
filePath = "/iTunes";
}else if(prefix.equals(".macho")){
filePath = "/MARSRESCAN";
}else{
return "/wrong.html";
}
boolean res = FTPUtil.uploadFile(host, port, userName, password, basePath, filePath, newName, in);
boolean delete = storeFile.delete();
if(res && delete){
return "/success.html";
}
}catch (Exception e){
e.printStackTrace();
}
return "/wrong.html";
}
private String byte2Hex(byte[] bytes) {
StringBuffer stringBuffer = new StringBuffer();
String temp = "";
for (int i = 0; i < bytes.length; i++) {
temp = Integer.toHexString(bytes[i] & 0XFF);
if(temp.length() == 1){
stringBuffer.append("0");
}
stringBuffer.append(temp);
}
return stringBuffer.toString();
}
}
FTPUtil
用來連接ftp服務(wù)器 上傳文件麻捻。
具體測試的時候可以在自己本機搭建一個ftp server 百度有教程
basePath 服務(wù)器的根目錄
filePath 文件的存放文件夾
package com.example.demo.util;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import java.io.IOException;
import java.io.InputStream;
public class FTPUtil {
public static boolean uploadFile(String host, int port, String username, String password, String basePath,
String filePath, String filename, InputStream input) {
boolean result = false;
FTPClient ftp = new FTPClient();
try {
int reply;
ftp.connect(host, port);
ftp.login(username, password);
if (!ftp.changeWorkingDirectory(basePath+filePath)) {
//如果目錄不存在創(chuàng)建目錄
String[] dirs = filePath.split("/");
String tempPath = basePath;
for (String dir : dirs) {
if (null == dir || "".equals(dir)) continue;
tempPath += "/" + dir;
if (!ftp.changeWorkingDirectory(tempPath)) {
if (!ftp.makeDirectory(tempPath)) {
return result;
} else {
ftp.changeWorkingDirectory(tempPath);
}
}
}
}
//設(shè)置上傳文件的類型為二進制類型
ftp.setFileType(FTP.BINARY_FILE_TYPE);
//上傳文件
if (!ftp.storeFile(filename, input)) {
return result;
}
input.close();
ftp.logout();
result = true;
} catch (IOException e) {
e.printStackTrace();
} finally {
if (ftp.isConnected()) {
try {
ftp.disconnect();
} catch (IOException ioe) {
}
}
}
return result;
}
}
4 重要的配置文件
server:
port: 8088
spring:
resources:
static-locations: classpath:/templates
servlet:
multipart:
max-file-size: 200MB
max-request-size: 200MB
upload:
host: 10.64.167.95
port: 21
userName:
password:
basePath: /
總結(jié)
實現(xiàn)文件的上傳遇到兩個坑
1 html與controller之間的調(diào)用:
剛開始發(fā)現(xiàn)請求app/upload無法相應(yīng) 后來發(fā)現(xiàn)是IDEA的默認端口號是63342 html請求時用的不是80
將IDEA的默認端口號改過來就行了
2 這個坑沒法記錄 蘋果的catlinna系統(tǒng)似乎在讀取本地存儲文件上需要特殊設(shè)置 后來在win上開發(fā)就沒問題了