springMVC框架下——通用介面之圖片上傳介面
我所想要的圖片上傳介面是指伺服器端在完成圖片上傳後,返回一個可訪問的圖片地址。
spring mvc框架下圖片上傳非常簡單,如下
1 @RequestMapping(value="/uploadImg", method=RequestMethod.POST) 2 @ResponseBody 3 public String uploadImg(@RequestParam(value="img")MultipartFile img){ 4 File f = new File("/data/images"); 5 try{ 6 FileUtils.copyInputStreamToFile(img.getInputStream(), f);7 }catch(Exception e){ 8 e.printStackTrace(); 9 } 10 return "上傳成功"; 11 }
非常簡單吧!
1 <form action="http://localhost/component/common/uploadImg" method="post" enctype="multipart/form-data"> 2 頭像:<input type="file" name="img" /><br/> 3 <input type="image"src="./images/img_submit.gif" /> 4 </form>
以上僅僅只是能夠上傳檔案而已,而我們還要能返回一個圖片地址,這個圖片地址要能在瀏覽器中直接訪問,如下:
直接程式碼吧!
controller層
1 @RequestMapping(value="/uploadImg", method=RequestMethod.POST) 2 @ResponseBody 3 public String uploadImg(@RequestParam(value="img")MultipartFile img, HttpServletResponse response){View Code4 JSONObject result = new JSONObject(); 5 boolean flag = true; 6 try { 7 flag = pictureUploadService.upload(img, result); 8 } catch (Exception e) { 9 result.put("mess", "呼叫失敗"); 10 flag = false; 11 e.printStackTrace(); 12 } 13 result.put("flag", flag); 14 15 response.setContentType("text/html;charset=UTF-8"); 16 //解決跨域名訪問問題 17 response.setHeader("Access-Control-Allow-Origin", "*"); 18 19 return result.toString(); 20 }
service層
1 /** 2 * 上傳圖片 3 * @param file 4 * @param params 5 * @return 6 * @throws Exception 7 */ 8 public boolean upload(MultipartFile file, JSONObject params) throws Exception{ 9 //過濾合法的檔案型別 10 String fileName = file.getOriginalFilename(); 11 String suffix = fileName.substring(fileName.lastIndexOf(".")+1); 12 String allowSuffixs = "gif,jpg,jpeg,bmp,png,ico"; 13 if(allowSuffixs.indexOf(suffix) == -1){ 14 params.put("resultStr", "not support the file type!"); 15 return false; 16 } 17 18 //獲取網路地址、本地地址頭部 19 Properties config = new Properties(); 20 config.load(this.getClass().getClassLoader().getResourceAsStream("config.properties")); 21 String urlPath = config.getProperty("urlRoot"); 22 String localPath = config.getProperty("localRoot"); 23 24 //建立新目錄 25 String uri = File.separator + DateUtil.getNowDateStr(File.separator); 26 File dir = new File(localPath + uri); 27 if(!dir.exists()){ 28 dir.mkdirs(); 29 } 30 31 //建立新檔案 32 String newFileName = StringUtil.getUniqueFileName(); 33 File f = new File(dir.getPath() + File.separator + newFileName + "." + suffix); 34 35 //將輸入流中的資料複製到新檔案 36 FileUtils.copyInputStreamToFile(file.getInputStream(), f); 37 38 //建立Picture物件 39 Picture pic = new Picture(); 40 pic.setLocalPath(f.getAbsolutePath()); 41 pic.setName(f.getName()); 42 pic.setUrl(urlPath + uri.replace("\\", "/") + "/" + newFileName + "." + suffix); 43 pic.setAddTime(new Date()); 44 45 //插入到資料庫 46 //... 47 48 params.put("resultStr", pic.getUrl()); 49 50 return true; 51 }View Code
(暫時沒有dao層,我在properties中配置網路地址的域名以及本地檔案儲存目錄)
上傳檔案有幾個地方需要注意:
- 上傳檔案的中文亂碼(這個暫不考慮,畢竟要實現的是圖片上傳)
- 限制上傳檔案大小(檔案過大,會導致伺服器不堪重負),這個我們在spring mvc的配置檔案中進行限制
1 <beans:bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> 2 <beans:property name="defaultEncoding" value="utf-8" /> 3 <beans:property name="maxUploadSize" value="10485760000" /> 4 <beans:property name="maxInMemorySize" value="40960" /> 5 </beans:bean>
- 限制上傳檔案型別(這個我們在service層進行處理)
- 如果一個資料夾下面儲存超過1000個檔案,就會影響檔案訪問效能,所以上傳的檔案要分散儲存(這個分散策略有多種,不必拘泥於一種。我這裡偷懶用了年月日作為目錄層級)
1 /** 2 * 獲取當前日期字串 3 * @param separator 4 * @return 5 */ 6 public static String getNowDateStr(String separator){ 7 Calendar now = Calendar.getInstance(); 8 int year = now.get(Calendar.YEAR); 9 int month = now.get(Calendar.MONTH)+1; 10 int day = now.get(Calendar.DATE); 11 12 return year + separator + month + separator + day; 13 }
- 上傳成功後儲存的檔案不能重名(即檔名要唯一)
1 //生成唯一的檔名 2 public static String getUniqueFileName(){ 3 String str = UUID.randomUUID().toString(); 4 return str.replace("-", ""); 5 }
上傳圖片流程如下:
點選上傳後,返回
在瀏覽器中輸入上面的這個圖片地址訪問,然後出現
相關推薦
springMVC框架下——通用介面之圖片上傳介面
我所想要的圖片上傳介面是指伺服器端在完成圖片上傳後,返回一個可訪問的圖片地址。 spring mvc框架下圖片上傳非常簡單,如下 1 @RequestMapping(value="/uploadImg", method=RequestMethod.POST) 2 @ResponseBody
springMVC框架-圖片上傳介面
Controler層裡面程式碼內容 @RequestMapping(value="/uploadImg", method=RequestMethod.POST) @ResponseBody public String uploadImgController(@
Jfinal框架學習系列之圖片上傳
昨天學習了一下在jfianl中使用jsp,然後實現了一個基本的增刪改查的demo示例,今天瞭解了一下在jfinal中實現檔案上傳的功能,這裡配合 了uploadify實現圖片上傳。。。這裡只是可以簡單地實現上傳的功能,有的時候也需要自己進行壓縮處理,,,貌似視
ASP.NET Core WebAPI圖片上傳介面之整合IdentityServer4授權訪問(附原始碼)
點選上方“程式設計師大咖”,選擇“置頂公眾號”關鍵時刻,第一時間送達!來源:依樂祝cnblogs
HTML5 之圖片上傳預處理
context 處理 file url form view utf .get ctu <!DOCTYPE html><html lang="en"> <head> <title></title> <
【轉載】【JAVA秒會技術之圖片上傳】基於Nginx及FastDFS,完成圖片的上傳及展示
相互 沒有 con 性能 ext 存儲服務器 網絡 管理 代理配置 基於Nginx及FastDFS,完成商品圖片的上傳及展示 一、傳統圖片存儲及展示方式 存在問題: 1)大並發量上傳訪問圖片時,需要對web應用做負載均衡,但是會存在圖片共享問題 2)web應
小程序之圖片上傳
span let clas stat path .get can pan gets //調用相冊等選擇圖片,得到圖片的相對路勁up_img: function () { var that = this; wx.chooseImage({
app端圖片上傳介面(tp5)
//檢視層 <div class="approve_NI_3"> <div class="approve_NI_3A"> &l
微信小微商戶圖片上傳介面
先貼上圖片上傳文件地址 https://pay.weixin.qq.com/wiki/doc/api/download/img_upload.pdf 圖片上傳介面返回的media_id在申請入駐介面時有用,所以一開始就得把這個調通,才能繼續往下走申請入駐介面。 下面直接上
Asp.NetCoreWebApi圖片上傳介面(二)整合IdentityServer4授權訪問(附原始碼)
寫在前面 本文地址:http://www.cnblogs.com/yilezhu/p/9315644.html 作者:yilezhu 上一篇關於Asp.Net Core Web Api圖片上傳的文章使用的是mongoDB進行圖片的儲存,文章釋出後,張隊就來了一句,說沒有使用GridFS。的確博主只是進行了簡
tp5中圖片上傳介面
1:移動端頁面:2:表單:重點圖片的uploadFile()事件<div id="approve_NI"> <div class="approve_NI_top"> <div class="approve_NI_top2"&g
微信小程式開發之圖片上傳+Java服務端接收 好不好使有待確認
閒言少敘直入正題存放路徑:/root/apache-tomcat-8.5.30/webapps/images/xxx.jpg前端程式碼在網上一搜一大堆,且搜出來的結果基本上是正確的,沒啥好說的,我連程式碼都不想貼(如果有時間的話明天整理下貼在文章結尾,沒時間的話就不貼了)。但是,但是,但是,靠譜的,不用改動就
TP5之圖片上傳
TP5 圖片上傳 HTML程式碼如下: <input name="photo" type="file" onchange="showPreview(this)"/> TP5控制器
vue元件開發之圖片上傳本地預覽元件
最近專案一直在使用vue,以前只是用vue做過一些簡單的demo對資料進行增刪改,並沒有用於實際開發專案,。今天就想了一下如何用vue實現常見的圖片上傳前本地預覽效果。 效果預覽: <template> <div class
PHP之圖片上傳到伺服器、上傳的錯誤型別
檔案上傳:資料從瀏覽器傳到伺服器; 檔案就是表單中資料的一部分,提交表單時,瀏覽器自動提交資料到伺服器,包括檔案在內; 表單上傳圖片 臨時目錄中的臨時檔案有有效期,預設是腳本週期(即一次請求結束); 下面是上傳後的檔案資訊: 需要將臨時上傳檔案持久化儲存,將其移
PHP 圖片上傳 (AIP圖片上傳介面,視訊上傳同理,只需改動jpg,png等為mp4,flv等)
PHP上傳的簡單案例: Html檔案:<html> <form action="index.php" name="form" method="post" enctype="multipart/form-data"> <input ty
Android、IOS 圖片上傳介面(Java實現Servlet)。
package com.ninepoint.babystar.server.action; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; imp
nodejs微信支付小微商戶申請入駐時,如何實現圖片上傳介面
微信支付小微商戶可以通過小程式《微信買單服務商助手》來進件,也可以通過API介面來進件(詳情可查閱小微商戶專屬介面文件)。 通過API介面進件前需要先在商戶資料中的身份證照片和門店照片通過圖片上傳介面上傳到微信的伺服器,並獲取media_id。 圖片上傳介面文件是這樣寫的
ASP.NET學習筆記(二)——一般處理程式之圖片上傳
簡單圖片上傳功能 目標:實現從本地磁碟讀取圖片檔案,展示到瀏覽器頁面。 步驟: (1). 首先建立一個用於上傳圖片的HTML模板,命名為ImageUpload.html: <!DOCTYPE html> <html> <h
SSM框架修改資料中實現圖片上傳功能
第一步:當然是需要加入必要的兩個jar包 commons-fileupload-1.3.jar、commons-io-1.2.jar 或者引入依賴: <dependency> <groupId>commons-