Java實(shí)現(xiàn)圖片上傳至FastDFS入門教程
今天來(lái)開(kāi)始寫圖片上傳的功能, 現(xiàn)在的圖片上傳都講求 上傳完成后立刻回顯且頁(yè)面不刷新, 這里到底是怎么做的呢? 當(dāng)然是借助于ajax了, 但是ajax又不能提交表單, 這里我們還要借助一個(gè)插件: jquery.form.js
剩下的一個(gè)是FastDFS, 那么什么是FastDFS呢?
FastDFS是一個(gè)開(kāi)源的輕量級(jí)分布式文件系統(tǒng),由跟蹤服務(wù)器(tracker server)、存儲(chǔ)服務(wù)器(storage server)和客戶端(client)三個(gè)部分組成,主要解決了海量數(shù)據(jù)存儲(chǔ)問(wèn)題,特別適合以中小文件(建議范圍:4KB < file_size <500MB)為載體的在線服務(wù)。
這里只來(lái)說(shuō)FastDFS的優(yōu)點(diǎn):
解決了大容量存儲(chǔ)和負(fù)載均衡的問(wèn)題。特別適合以文件為載體的在線服務(wù),如相冊(cè)網(wǎng)站、視頻網(wǎng)站等等。
FastDFS服務(wù)端有兩個(gè)角色:跟蹤器(tracker)和存儲(chǔ)節(jié)點(diǎn)(storage)。跟蹤器主要做調(diào)度工作,在訪問(wèn)上起負(fù)載均衡的作用。
更多詳細(xì)內(nèi)容可以參考:http://blog.chinaunix.net/uid-20196318-id-4058561.html
一, 開(kāi)發(fā)實(shí)例
0, 使用FastDFS:
首先需要在Linux下安裝且配置FastDFS, 這里不再贅述.
首先來(lái)看下引入的FastDFS jar包:
查看fdfs_client.conf配置文件:
我們發(fā)現(xiàn)這里面的設(shè)置不是我們想要的, 那么該怎么辦呢? 我們需要在自己工程中覆蓋一份:
配置文件內(nèi)容如下:(這里需要配置tracker_server)
# connect timeout in seconds # default value is 30s connect_timeout=30 # network timeout in seconds # default value is 30s network_timeout=60 # the base path to store log files base_path=/home/fastdfs # tracker_server can ocur more than once, and tracker_server format is # "host:port", host can be hostname or ip address tracker_server=192.168.200.128:22122 #tracker_server=192.168.101.4:22122 #standard log level as syslog, case insensitive, value list: ### emerg for emergency ### alert ### crit for critical ### error ### warn for warning ### notice ### info ### debug log_level=info # if use connection pool # default value is false # since V4.05 use_connection_pool = false # connections whose the idle time exceeds this time will be closed # unit: second # default value is 3600 # since V4.05 connection_pool_max_idle_time = 3600 # if load FastDFS parameters from tracker server # since V4.05 # default value is false load_fdfs_parameters_from_tracker=false # if use storage ID instead of IP address # same as tracker.conf # valid only when load_fdfs_parameters_from_tracker is false # default value is false # since V4.05 use_storage_id = false # specify storage ids filename, can use relative or absolute path # same as tracker.conf # valid only when load_fdfs_parameters_from_tracker is false # since V4.05 storage_ids_filename = storage_ids.conf #HTTP settings http.tracker_server_port=80 #use "#include" directive to include HTTP other settiongs ##include http.conf
1, 在jsp中添加input標(biāo)簽上傳圖片
這里有一個(gè)隱藏域字段是imgUrl, 這里是保存上傳圖片成功后返回的圖片地址, 在submit整個(gè)表單時(shí), 將這個(gè)url地址保存到數(shù)據(jù)庫(kù), 在list.jsp中直接取這個(gè)url就可以回顯圖片數(shù)據(jù)了.
2, 添加上傳js 代碼:
這里使用到了ajaxSubmit方法, 當(dāng)我們上傳圖片時(shí)實(shí)際上是將表單提交了, 然后通過(guò)UploadPicController中的uploadPic方法去處理發(fā)送的請(qǐng)求.
3, 構(gòu)建uploadPicController.cs去解析uploadPic.do請(qǐng)求
Controller層:
UploadController.java:
* 上傳圖片 */ @Controller @RequestMapping(value="/upload") public class UploadController { @Autowired private UploadService uploadService; //上傳圖片品牌 @RequestMapping(value="/uploadPic.do") public void uploadPic(@RequestParam(required=false) MultipartFile pic, HttpServletResponse response) throws Exception{ //Java接口連接FastDFS String path = uploadService.uploadPic(pic.getBytes(), pic.getOriginalFilename(), pic.getSize()); //path:group1/M00/00/01/wKjIgFWOYc6APpjAAAD-qk29i78248.jpg //url:http://192.168.200.128 (Linux 虛擬機(jī)的ip地址) String url = Constants.img_url + path; //Json工具類 JSONObject jo = new JSONObject(); jo.put("url", url); jo.put("path", path); //返回json response.setContentType("application/json;charset=UTF-8"); response.getWriter().write(jo.toString()); } }
通過(guò)json的格式將url寫回到前端, 這樣在ajax請(qǐng)求中就可以接收到參數(shù)并回顯圖片.
Service層:
UploadServiceImpl.java:
/* * 上傳圖片 */ @Service("uploadService") public class UploadServiceImpl implements UploadService { //上傳 public String uploadPic(byte[] pic, String name, long size){ return FastDFSUtils.uploadPic(pic, name, size); } }
Common工具類:
FastDFSUtils.cs
/* *上傳FastDFS圖片 */ public class FastDFSUtils { public static String uploadPic(byte[] pic, String name, long size){ String path = null; //ClassPath下的文件Spring ClassPathResource resource = new ClassPathResource("fdfs_client.conf"); try { ClientGlobal.init(resource.getClassLoader().getResource("fdfs_client.conf").getPath()); //客服端 TrackerClient trackerClient = new TrackerClient(); TrackerServer trackerServer = trackerClient.getConnection(); //連接小弟 StorageClient1 storageClient1 = new StorageClient1(); //擴(kuò)展名, 獲取擴(kuò)展名, apach 下common包中已有公用方法. String extension = FilenameUtils.getExtension(name); //設(shè)置圖片meta信息 NameValuePair[] meta_list = new NameValuePair[3]; meta_list[0] = new NameValuePair("filename", name); meta_list[1] = new NameValuePair("fileext", extension); meta_list[2] = new NameValuePair("filesize", String.valueOf(size)); //上傳且返回path path = storageClient1.upload_file1(pic, extension, meta_list); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return path; } }
這里是FastDFS的核心方法, 這里將tracker比喻成老大,將storage比喻成小弟. 且為這個(gè)圖片添加 一些meta信息, 最后調(diào)用upload_file1 將圖片上傳到圖片服務(wù)器且返回path.
整個(gè)開(kāi)發(fā)流程就是這樣, 記錄于此 愿日后回顧復(fù)習(xí)能夠有更大的收獲.
上面我們已經(jīng)說(shuō)到ajax請(qǐng)求異步上傳, 那么這里我們?cè)賮?lái)說(shuō)下多圖片上傳, 如果單張圖片上傳已經(jīng)搞清楚的話,那么單圖片上傳就顯得很簡(jiǎn)單了.
首先我們繼續(xù)來(lái)查看jsp頁(yè)面:
這個(gè)js用來(lái)處理點(diǎn)擊上傳后做的事情, 其中回顯數(shù)據(jù)使用了從controller層接收回來(lái)的數(shù)據(jù), 然后使用foreach進(jìn)行遍歷, 那么接下來(lái)我們來(lái)看下controller層做的事情:
//上傳多張圖片 @RequestMapping(value="/uploadPics.do") public @ResponseBody List<String> uploadPics(@RequestParam(required=false) MultipartFile[] pics, HttpServletResponse response) throws Exception{ //多張圖片的路徑容器 List<String> paths = new ArrayList<String>(); for (MultipartFile pic : pics) { //Java接口連接FastDFS String path = uploadService.uploadPic(pic.getBytes(), pic.getOriginalFilename(), pic.getSize()); paths.add(Constants.img_url+path); } return paths; }
使用foreach將圖片的url地址全部都裝載到一個(gè)list集合中, 然后返回給ajax請(qǐng)求函數(shù).
Service層:
@Service("uploadService") public class UploadServiceImpl implements UploadService { //上傳 public String uploadPic(byte[] pic, String name, long size){ return FastDFSUtils.uploadPic(pic, name, size); } }
一切都還是老樣子, 只不過(guò) controller層和jsp都是用了foreach去遍歷, 而且jsp中多加了一個(gè)屬性:multiple="multiple". 僅此而已.
到此這篇關(guān)于Java實(shí)現(xiàn)圖片上傳至FastDFS入門教程的文章就介紹到這了,更多相關(guān)Java圖片上傳至FastDFS內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- Java實(shí)現(xiàn)整合文件上傳到FastDFS的方法詳細(xì)
- Java 客戶端操作 FastDFS 實(shí)現(xiàn)文件上傳下載替換刪除功能
- Java fastdfs客戶端實(shí)現(xiàn)上傳下載文件
- Java使用OSS實(shí)現(xiàn)上傳文件功能
- Java下載https文件并上傳阿里云oss服務(wù)器
- Java微信小程序oss圖片上傳的實(shí)現(xiàn)方法
- java實(shí)現(xiàn)上傳文件到oss(阿里云)功能示例
- java獲取網(wǎng)絡(luò)圖片上傳到OSS的方法
- Java實(shí)現(xiàn)Fast DFS、服務(wù)器、OSS上傳功能
相關(guān)文章
Java Config下的Spring Test幾種方式實(shí)例詳解
這篇文章主要介紹了Java Config下的Spring Test方式實(shí)例代碼的相關(guān)資料,需要的朋友可以參考下2017-05-05Springboot非分布式定時(shí)任務(wù)實(shí)現(xiàn)代碼
這篇文章主要介紹了Springboot非分布式定時(shí)任務(wù)實(shí)現(xiàn)代碼,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-11-11Java 使用json-lib處理JSON詳解及實(shí)例代碼
這篇文章主要介紹了Java 使用json-lib處理JSON詳解及實(shí)例代碼的相關(guān)資料,需要的朋友可以參考下2017-02-02java多線程編程之向線程傳遞數(shù)據(jù)的三種方法
在多線程的異步開(kāi)發(fā)模式下,數(shù)據(jù)的傳遞和返回和同步開(kāi)發(fā)模式有很大的區(qū)別。由于線程的運(yùn)行和結(jié)束是不可預(yù)料的,因此,在傳遞和返回?cái)?shù)據(jù)時(shí)就無(wú)法象函數(shù)一樣通過(guò)函數(shù)參數(shù)和return語(yǔ)句來(lái)返回?cái)?shù)據(jù)2014-01-01