【SpringBoot】上傳圖片到Linux伺服器(html+ajax+jquery+ftpclient+nginx)
最近在做畢業設計,需要做一個批量上傳圖片的功能。
先介紹一下,前端的程式碼:
①在前端html中使用file型別的input標籤,
<input type="file" multiple="multiple" id="uploadImages">
②js操作,獲取file,存在一個fileStack陣列中,並通過,jquery each方法,將圖片回寫
到Html中。
$(function() { // 圖片上傳 fileStack = [];// 存放圖片檔案的陣列 // 當<input type="file">change時呼叫addFiles() $("#uploadImages").change(function() { addFiles(); }) // 刪除操作,操作這個fileStack function addFiles() { var files = document.querySelector("input[type=file]"); var filelist = files.files;// 選擇圖片列表 $.each(filelist,function(i, file) {fileStack.push(file); var reader = new FileReader(); reader.onload = function(e) { var result = this.result; var img = document.createElement("img"); // img.src = result; var i = 0; $("#imagesUl").append("<li class='img_box' data-index='" + (i++) + "' draggable='true'><img src='" + result + "'><div class='img_cover'></div><div class='toolbar_wrap'>" + "<div class='opacity'></div>" + "<div class='toolbar'>" + "<a href='javascript:;' class='edit'></a><a href='javascript:;' class='delete'></a></div></div></li>"); }; reader.readAsDataURL(file); }); } })
③提交資料到後臺,用each方法將上述fileStack陣列新增到formdata中
var formdata = new FormData();//定義一個formdata物件
$.each(fileStack, function(i, file) {// 所有檔案都要放到同一個名字下面:如files
formdata.append("file", file);
});
function submitMethod(formdata) { $.ajax({ type : 'POST', url : "/tenement/uploadImages.action", dataType : 'json', data : formdata, cache : false, processData : false, contentType : false, success : function(responseStr) { if (responseStr == "1") { swal("釋出成功,資訊稽核中", "", "success"); } else { swal("釋出失敗,未知錯誤", "", "error"); } }, error : function(responseStr) { swal("釋出失敗,未知錯誤", "", "error"); } }); }
後臺程式碼:
Controller層程式碼:
/** * 資料上傳 * * @param albumId * @param files * @return * @throws IOException */ @RequestMapping("/uploadImages.action") public @ResponseBody String uploadFiles(@RequestParam("albumId") Integer albumId, @RequestParam("file") MultipartFile[] files) throws IOException { logger.info("【上傳圖片controller】"); FtpConfig ftpConfig = new FtpConfig(); List<Photo> photoList = new ArrayList<Photo>(); for (MultipartFile file : files) { Photo photo = new Photo(); String oldName = file.getOriginalFilename();// 獲取圖片原來的名字 String picNewName = UploadUtils.generateRandonFileName(oldName);// 通過工具類產生新圖片名稱,防止重名 String picSavePath = UploadUtils.generateRandomDir(picNewName);// 通過工具類把圖片目錄分級 /* * photo.setPhotoUrl(picSavePath + "/");// * 設定圖片的url--》就是儲存到資料庫的字串url photo.setAlbumId(albumId);// * 設定圖片所屬相簿id photo.setUser_id("wk"); * photo.setPhoteName(picNewName); */ photoList.add(photo); FtpUtil.pictureUploadByConfig(ftpConfig, picNewName, picSavePath, file.getInputStream());// 上傳到圖片伺服器的操作 // 新增到資料庫 } iPhotoService.uploadImages(photoList); return state.Success; }
UploadUtils.java,獲得檔案新名字,生成一二級目錄
package com.tenement.utils.ftp_images_server;
import java.io.File;
import java.util.UUID;
public class UploadUtils {
/**
* 得到真實檔名
*
* @param fileName
* @return
*/
public static String subFileName(String fileName) {
// 查詢最後一個 \ (檔案分隔符)位置
int index = fileName.lastIndexOf(File.separator);
if (index == -1) {
// 沒有分隔符,說明是真實名稱
return fileName;
} else {
return fileName.substring(index + 1);
}
}
/**
* 獲得隨機UUID檔名
*
* @param fileName
* @return
*/
public static String generateRandonFileName(String fileName) {
// 首相獲得副檔名,然後生成一個UUID碼作為名稱,然後加上副檔名
String ext = fileName.substring(fileName.lastIndexOf("."));
return UUID.randomUUID().toString() + ext;
}
public static String generateRandonFileName() {
return UUID.randomUUID().toString();
}
/**
* 獲得hashcode 生成二級目錄
*
* @param uuidFileName
* @return
*/
public static String generateRandomDir(String uuidFileName) {
int hashCode = uuidFileName.hashCode();// 得到它的hashcode編碼
// 一級目錄
int d1 = hashCode & 0xf;
// 二級目錄
int d2 = (hashCode >> 4) & 0xf;
return "/" + d1 + "/" + d2;
}
public static void main(String[] args) {
System.out.println(generateRandonFileName());
}
}
FtpUtil.java,上傳檔案到伺服器上的工具類
package com.tenement.utils.ftp_images_server;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
/**
* 正在使用
* @author wk
*
*/
public class FtpUtil {
private static final Log logger = LogFactory.getLog(FtpUtil.class);
public static String pictureUploadByConfig(FtpConfig ftpConfig, String picNewName, String picSavePath,
InputStream inputStream) throws IOException {
logger.info("【pictureUploadByConfig】");
String picHttpPath = null;
boolean flag = uploadFile(ftpConfig.getFTP_ADDRESS(), ftpConfig.getFTP_PORT(), ftpConfig.getFTP_USERNAME(),
ftpConfig.getFTP_PASSWORD(), ftpConfig.getFTP_BASEPATH(), picSavePath, picNewName, inputStream);
if (!flag) {
return picHttpPath;
}
picHttpPath = ftpConfig.getIMAGE_BASE_URL() + picSavePath + "/" + picNewName;
logger.info("【picHttpPath】"+picHttpPath);
return picHttpPath;
}
/**
* Description: 向FTP伺服器上傳檔案
*
* @param host
* FTP伺服器hostname
* @param port
* FTP伺服器埠
* @param username
* FTP登入賬號
* @param password
* FTP登入密碼
* @param basePath
* FTP伺服器基礎目錄
* @param filePath
* FTP伺服器檔案存放路徑。
* @param filename
* 上傳到FTP伺服器上的檔名
* @param input
* 輸入流
* @return 成功返回true,否則返回false
*/
public static boolean uploadFile(String host, String ftpPort, String username, String password, String basePath,
String filePath, String filename, InputStream input) {
int port = Integer.parseInt(ftpPort);
boolean result = false;
FTPClient ftp = new FTPClient();
try {
int reply;
ftp.connect(host, port);// 連線FTP伺服器
// 如果採用預設埠,可以使用ftp.connect(host)的方式直接連線FTP伺服器
ftp.login(username, password);// 登入
reply = ftp.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
ftp.disconnect();
return result;
}
// 切換到上傳目錄
if (!ftp.changeWorkingDirectory(basePath + filePath)) {
// 如果目錄不存在建立目錄
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);
}
}
}
}
// 設定上傳檔案的型別為二進位制型別
ftp.setFileType(FTP.BINARY_FILE_TYPE);
ftp.enterLocalPassiveMode();// 這個設定允許被動連線--訪問遠端ftp時需要
// 上傳檔案
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;
}
}
FtpConfig.java實體類
package com.tenement.utils.ftp_images_server;
/**
* ftp伺服器配置實體類
*
* @author wk
*
*/
public class FtpConfig {
/**
* 獲取IP地址
*/
private String FTP_ADDRESS = "伺服器ip地址";
/**
* 埠號
*/
private String FTP_PORT = "21";
/**
* 使用者名稱
*/
private String FTP_USERNAME = "ftp使用者名稱";
/**
* 密碼
*/
private String FTP_PASSWORD = "ftp使用者密碼";
/**
* 基本路徑,使用者圖片
*/
private String FTP_BASEPATH = "/home/ftptest/tenement/house_images";
/**
* 下載地址地基礎url,這個是配置的圖片伺服器的地址,最後訪問圖片時候,需要用該基礎地址
*/
private String IMAGE_BASE_URL = "url";
public String getFTP_ADDRESS() {
return FTP_ADDRESS;
}
public void setFTP_ADDRESS(String fTP_ADDRESS) {
FTP_ADDRESS = fTP_ADDRESS;
}
public String getFTP_PORT() {
return FTP_PORT;
}
public void setFTP_PORT(String fTP_PORT) {
FTP_PORT = fTP_PORT;
}
public String getFTP_USERNAME() {
return FTP_USERNAME;
}
public void setFTP_USERNAME(String fTP_USERNAME) {
FTP_USERNAME = fTP_USERNAME;
}
public String getFTP_PASSWORD() {
return FTP_PASSWORD;
}
public void setFTP_PASSWORD(String fTP_PASSWORD) {
FTP_PASSWORD = fTP_PASSWORD;
}
public String getIMAGE_BASE_URL() {
return IMAGE_BASE_URL;
}
public void setIMAGE_BASE_URL(String iMAGE_BASE_URL) {
IMAGE_BASE_URL = iMAGE_BASE_URL;
}
public String getFTP_BASEPATH() {
return FTP_BASEPATH;
}
public void setFTP_BASEPATH(String fTP_BASEPATH) {
FTP_BASEPATH = fTP_BASEPATH;
}
}
在這之前在專案pom.xml引入相關jar包
<!-- 加入上傳檔案元件 -->
<!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3</version>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-net/commons-net -->
<dependency>
<groupId>commons-net</groupId>
<artifactId>commons-net</artifactId>
<version>3.3</version>
</dependency>
整體思路:
前臺獲取獲取file陣列,傳到後臺,使用ftpclient類,將file傳到linux伺服器
上,在資料庫中儲存的是圖片的一二級目錄和圖片新名字。
最後訪問時通過nginx反向代理功能來訪問伺服器上的圖片
如何利用Nginx搭建圖片伺服器參照部落格:
相關推薦
【SpringBoot】上傳圖片到Linux伺服器(html+ajax+jquery+ftpclient+nginx)
最近在做畢業設計,需要做一個批量上傳圖片的功能。 先介紹一下,前端的程式碼: ①在前端html中使用file型別的input標籤, <input type="file" multiple="multiple" id="uploadImages"> ②js操
【jmeter】上傳圖片request payload的實現方法
1.首先抓包的資料是這樣的 2.jmeter各項的配置 3.新增HTTP 3.注意: implementation選擇java; files upload MIME型別image/jpeg; 引數名稱file;
微信小程式如何上傳圖片至伺服器(node.js例項分享)
一、前臺處理 (1)首先在wxml中為按鈕繫結上傳圖片事件 <button bindtap="upImgClick">上傳圖片</button> <image src='{{imgUrl}}'></image>
用HTML5獲取攝像頭影象,並且上傳圖片到伺服器(程式碼完整可用)
前面轉載的那篇文章,HTML 5線上攝像頭應用,直接使用例子來測試有問題(我直接部署到伺服器上,使用Chrome瀏覽器執行),所以我參考它的原始碼重新整理了一個頁面出來,這個在Chrome(版本 29.0.1547.76 m)測試過,應該沒有問題。 這個版本的程式碼是最簡
將Windows本機的thinkPHP專案上傳到Linux伺服器(阿里雲伺服器)
之前還沒買伺服器的時候,同學將他的伺服器借我玩玩,我就將自己之前寫的thinkPHP簡陋的部落格專案上傳到上面試了一下, 雖然也碰到錯誤,最後通過百度都成功解決,詳見前面的博文。前幾天買
上傳圖片裁剪外掛(基於cropper.js的封裝)
如題,這樣的功能在開發中是非常常見的,cropper.js是一款很好的工具,網上都有詳細的介紹,這篇文章提示很多友好的API和事件cropper.js 裁剪圖片並上傳(文件翻譯+demo) cropper.js需要藉助jquery來實現,所以我這裡的樣式抄襲了
Springboot (打成jar執行)上傳圖片到伺服器,客戶端可直接通過url訪問
本地測試時,直接上傳圖片到resources/static 檔案下沒有問題,但是打成jar後,直接報錯 @RequestMapping(value = "/oldUploadImage",method = RequestMethod.POST) p
springboot(7)——上傳圖片/檔案到七牛雲端儲存
一、七牛雲快速入門 快速入門 1、註冊賬號 2、建立儲存空間, 命名xyz對應下面springboot 應用配置bucket 3、建立成功後進入該空間,獲取該空間的測試域名,對應下面springboot 應用配置中的path 4、點選“個人面板—金鑰管理
SpringBoot+WangEditor上傳圖片
今天本地在除錯一個問題,,wangEditor這個富文字編輯器上傳圖片,其實上傳圖片到也沒有什麼困難的地方,關鍵是在於,後臺是SpringBoot來進行接收圖片,,不說了直接上程式碼:這個是前端的程式碼: var editor = new wangEditor('#txtDiv'); edi
vue-quill-editor-upload : 實現vue-quill-editor上傳圖片到伺服器
vue-quill-editor-upload git: https://github.com/NextBoy/vu... A plug-in for uploading images to your server when you use vue-quill-editor. 富文字編輯器vue-qui
如何將本地檔案通過終端上傳到linux伺服器 /伺服器/阿里雲
scp -P 埠 c://xxxx.txt [email protected]:/home/root 注意: -P 大寫 -i 公鑰 (我是將檔案上傳到阿里雲) (1)在本地的終端下,而不是在伺服器上。在本地的終端上才能將本地的檔案拷入伺服器。 (2)
wangedit上傳圖片的伺服器
後臺 @ApiOperation(notes = "返回一個檔名,需要呼叫 /home/download方法才可以獲取到檔案", httpMethod = "POST", value = "檔案/圖片上傳") @RequestMapping("/uploaderPic2") @Respon
vue 整合ueditor(百度富文字編輯器)以及使用後端Java上傳圖片到伺服器,特別注意的大坑
1.import 引入ueditor時,在封裝元件中引入,不要在mian.js內引入,在main.js內引入會造成 1.Uncaught SyntaxError: Unexpected token : 這種錯誤,屬於是跨域問題,目前不清楚是什麼原因和原理,
上傳圖片到伺服器,並且重新命名圖片-更改(小白共勉)
實現使用者註冊功能,使用者上傳頭像放在imgs的目錄下,所涉及檔案分別是register.html(註冊),conn.php(連線資料庫),img.php(上傳圖片與更改圖片名稱,改成了是一個函式,返回 圖片儲存位置+圖片名稱),register.php(註冊功能) register.html介
上傳圖片到伺服器,並且重新命名圖片(小白共勉)
根據教程上更改的,含冗餘,會再改,小白共勉 檔案所含內容如下(不知道為啥編輯器不能給字型改變顏色了,鬱悶): upload資料夾為存放圖片資料夾,注意upload、imgnewname.php、index.html、upload_file.php為同一級、 為了可以多次呼叫更改名稱
JAVA使用JSCH實現檔案上傳到linux伺服器
1 匯入jar包 <dependency> <groupId>com.jcraft</groupId> <artifactId>jsch</artifactId> <version
Android上傳圖片到伺服器並顯示(後臺用Java處理)
Android上傳圖片(Android Studio) Fragment介面: private String img_src; /** * 從相簿選取圖片 */ public void selectImg() { Intent intent = new
本地檔案上傳到Linux伺服器的幾種方法
本文介紹幾種常見的方法,把檔案上傳到Linux伺服器中! 常見有使用:scp命令、xshell軟體裡的xftp程式、U盤掛載、伺服器自帶的lrzsz程式。 一、scp使用說明: 1、把本機的檔案傳給
用form表單提交方式上傳圖片到伺服器
springMVC為檔案上傳提供了直接的支援,這種支援是通過MultipartResolver實現的,實現類為CommonsMultipartResovler. 依賴:commons-fileupload-1.2.jar commons-io-1.
使用SecureCRT來上傳下載Linux伺服器檔案
SecureCRT下的檔案傳輸協議有以下幾種:ASCII、Xmodem、Ymodem、Zmodem ASCII:這是最快的傳輸協議,但只能傳送文字檔案。 Xmodem:這種古老的傳輸協議速度較慢,但由於使用了CRC錯誤偵測方法,傳輸的準確率可高達99.6%。 Ymodem:這是X