spring boot使用nginx和ftp伺服器實現圖片上傳下載(windows server)
阿新 • • 發佈:2019-01-02
本人使用的springboot為1.5.6版本
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.6.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
maven依賴為:
<commons-lang3.version>3.3.2</commons-lang3.version> <commons-io.version>1.3.2</commons-io.version> <commons-net.version>3.3</commons-net.version> <commons-fileupload.version>1.3.1</commons-fileupload.version>
<!-- <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> <!--啟用不嚴格檢查html --> <dependency> <groupId>net.sourceforge.nekohtml</groupId> <artifactId>nekohtml</artifactId> <version>1.9.22</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <!-- Apache工具元件 --> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>${commons-lang3.version}</version> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-io</artifactId> <version>${commons-io.version}</version> </dependency> <dependency> <groupId>commons-net</groupId> <artifactId>commons-net</artifactId> <version>${commons-net.version}</version> </dependency> <!-- httpclient --> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>${httpclient.version}</version> </dependency> <!-- MySql --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>${mysql.version}</version> </dependency> <!-- 連線池 --> <!-- Spring --> <!-- 檔案上傳元件 --> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>${commons-fileupload.version}</version> </dependency>
application.properties配置:
#ftp\u76F8\u5173\u914D\u7F6E FTP_ADDRESS=你的伺服器 FTP_PORT=商品 FTP_USERNAME=你的使用者名稱 FTP_PASSWORD=你的密碼 FTP_BASE_PATH=images #\u56FE\u7247\u670D\u52A1\u5668\u76F8\u5173\u914D\u7F6E IMAGE_BASE_URL=images NG_BASE_PATH=10021 server.port=8015 server.context-path=/demo spring.thymeleaf.mode=LEGACYHTML5
controller:
@ResponseBody
@RequestMapping("upload")
public String pictureUpload(@RequestParam(value = "file") MultipartFile uploadFile) {
long begin = System.currentTimeMillis();
String json = "";
try {
Map result = pictureService.uploadPicture(uploadFile);
// 瀏覽器擅長處理json格式的字串,為了減少因為瀏覽器核心不同導致的bug,建議用json
json = new ObjectMapper().writeValueAsString(result);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
long end = System.currentTimeMillis();
log.info("定時任務結束,共耗時:[" + (end-begin) + "]毫秒");
return json;
}
service:
@Override
public Map uploadPicture(MultipartFile uploadFile) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
String date = sdf.format(new Date());
Map resultMap = new HashMap<>();
try {
// 1. 取原始檔名
String oldName = uploadFile.getOriginalFilename();
String suffix = oldName.substring(oldName.lastIndexOf(".") + 1, oldName.length());
// 2. ftp 伺服器的檔名
String newName = date + "." + suffix;
// 圖片上傳
boolean result = uploadFile(FTP_ADDRESS, FTP_PORT, FTP_USERNAME, FTP_PASSWORD, uploadFile.getInputStream(),
FTP_BASE_PATH, newName);
// 返回結果
if (!result) {
resultMap.put("error", 1);
resultMap.put("message", "upload Fail");
return resultMap;
}
resultMap.put("error", 0);
resultMap.put("url", IMAGE_BASE_URL + "/" + newName);
return resultMap;
} catch (Exception e) {
e.printStackTrace();
resultMap.put("error", 1);
resultMap.put("message", "upload Fail");
return resultMap;
}
}
/**
* ftp 上傳圖片方法
*
* @param ip
* ftp 伺服器ip地址
* @param port
* ftp 伺服器port,預設是21
* @param account
* ftp 伺服器使用者名稱
* @param passwd
* ftp 伺服器密碼
* @param inputStream
* 檔案流
* @param workingDir
* ftp 伺服器儲存圖片的絕對路徑
* @param fileName
* 上傳到ftp 伺服器檔名
* @throws Exception
*
*/
public boolean uploadFile(String ip, Integer port, String account, String passwd, InputStream inputStream,
String workingDir, String fileName) throws Exception {
boolean result = false;
// 1. 建立一個FtpClient物件
FTPClient ftpClient = new FTPClient();
try {
// 2. 建立 ftp 連線
ftpClient.connect(ip, port);
// 3. 登入 ftp 伺服器
ftpClient.login(account, passwd);
int reply = ftpClient.getReplyCode(); // 獲取連線ftp 狀態返回值
System.out.println("code : " + reply);
if (!FTPReply.isPositiveCompletion(reply)) {
ftpClient.disconnect(); // 如果返回狀態不再 200 ~ 300 則認為連線失敗
return result;
}
// 4. 讀取本地檔案
// FileInputStream inputStream = new FileInputStream(new
// File("F:\\hello.png"));
// 5. 設定上傳的路徑
ftpClient.changeWorkingDirectory(workingDir);
// 6. 修改上傳檔案的格式為二進位制
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
// 7. 伺服器儲存檔案,第一個引數是儲存在伺服器的檔名,第二個引數是檔案流
if (!ftpClient.storeFile(fileName, inputStream)) {
return result;
}
// 8. 關閉連線
inputStream.close();
ftpClient.logout();
result = true;
} catch (Exception e) {
e.printStackTrace();
} finally {
// FIXME 聽說,專案裡面最好少用try catch
// 捕獲異常,這樣會導致Spring的事務回滾出問題???難道之前寫的程式碼都是假程式碼!!!
if (ftpClient.isConnected()) {
try {
ftpClient.disconnect();
} catch (IOException ioe) {
}
}
}
return result;
}
下面是nginx配置:
${nginx}/conf/nginx.conf中新增:
server {
listen 8088;
server_name localhost;
location / {
# 存放圖片的地址
root D:/images;
index *.*;
add_header Access-Control-Allow-Origin *;
add_header Access-Control-Allow-Headers X-Requested-With;
add_header Access-Control-Allow-Methods GET,POST,OPTIONS;
}
}
測試nginx:命令: nginx -t
配置ftp伺服器請百度。
end.