uploadify控制 上传图片到百度云存储
生活随笔
收集整理的這篇文章主要介紹了
uploadify控制 上传图片到百度云存储
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
最近使用uploadify 控制圖片上傳到百度網盤。。。。總的想法是 招待會uploadify獲取文件傳入后臺,調用百度云存儲api上傳到百度網盤,返回url 聯系。送存儲在數據庫中的鏈接。因此,我們有一個數據庫,這只是url ?真正的文件保存在百度云存儲這,常好用。這一個業務流程用到了uploadify 控件和百度云存儲。
流程例如以下:首先下載uploadify 包
這個不同文件混在一起還沒有分開。
。功能先實現再說。。。
前臺jsp頁面例如以下:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head><base href="<%=basePath%>"><title>加入幻燈片</title><meta http-equiv="pragma" content="no-cache"><meta http-equiv="cache-control" content="no-cache"><meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"><meta http-equiv="description" content="This is my page"><link rel="stylesheet" href="easyui/css/main.css" type="text/css" /><link rel="stylesheet" type="text/css" href="uploadify/uploadify.css" /><script type="text/javascript" src="uploadify/swfobject.js"></script><script type="text/javascript" src="js/jquery-1.11.0.min.js"></script><script type="text/javascript" src="uploadify/jquery.uploadify.min.js"></script><script type="text/javascript">$(function() {$("#uploadify").uploadify({'uploader' : '../schSlide/schSlide_addSchSlide.action', //是組件自帶的flash。用于打開選取本地文件的button 'script' : 'uploadify.php','fileObjName' : 'file','cancelImg' : 'uploadify/uploadify-cancel.png',//取消上傳文件的button圖片,就是個叉叉 'folder' : 'uploadify/uploads',//上傳文件的文件夾'queueID' : 'fileQueue','auto' : false,//是否選取文件后自己主動上傳'multi' : true,//是否支持多文件上傳'simUploadLimit' : 7,//每次最大上傳文件數'buttonText' : '選擇文件',//button上的文字'displayData' : 'speed',//有speed和percentage兩種。一個顯示速度,一個顯示完畢百分比 'fileDesc' : '支持格式:jpg/gif/jpeg/png/bmp.', //假設配置了下面的'fileExt'屬性。那么這個屬性是必須的 'fileExt' : '*.jpg;*.gif;*.jpeg;*.png;*.bmp',//同意的格式//'debug': true,'onComplete' : function (event, queueID, fileObj, response, data){$("#result").html(response);//顯示上傳成功結果setInterval("showResult()",2000);//兩秒后刪除顯示的上傳成功結果},'onError': function(event, queueID, fileObj) {$j("#result").css("color", "red");$j("#result").html("文件:" + fileObj.name + "上傳失敗");}});});function showResult(){//刪除顯示的上傳成功結果$("#result").html("");}function clearFile(){//清空全部上傳隊列$("#result").html("");}</script> </head> <body><div id="fileQueue"></div><p><input type="file" name="uploadify" id="uploadify" /></p><p><a onclick = "$('#uploadify').uploadify('upload','*');" href="javascript:void(0)">開始上傳</a>?</p><div id="result"></div><!--顯示結果--> </body> </html>調用schSlide/schSlide_addSchSlide.action來進行功能實現struts2 配置文件例如以下 <!-- 幻燈片模塊 --><package name="schSlide" namespace="/schSlide" extends="json-default"><action name="*_*" class="{1}Action" method="{2}"><result name="success">/backstage/b_schslide.jsp</result><result type="json" name="json"><param name="root">dataMap</param></result></action></package>action 的部分代碼例如以下省去get set 方法 private Map<String, Object> dataMap;private SchSlide schSlide;private int page;private int rows;private int schSlideId;private String name;private List<SchSlide> schSlideList;private File uploadify; private String uploadifyFileName;private File[] file;private String[] fileFileName;// 輸出文件地址private String url = "";// 上傳文件名稱private String fileName = "";// 原始文件名稱//private String originalName = "";// 文件類型private String type = "";private HttpServletRequest request = null;private String savePath = "uploadSlide";@Autowiredprivate SchSlideService schSlideService; //加入幻燈片public String addSchSlide() throws Exception{schSlide = new SchSlide();for (int i = 0; i < file.length; i++) { String savePath = this.getFolder(this.savePath);this.fileName = this.getName(fileFileName[i]);File tempFile = new File(savePath + "/" + this.fileName);tempFile.deleteOnExit();System.out.println(tempFile);FileOutputStream fos = new FileOutputStream(tempFile);FileInputStream bis = new FileInputStream(file[i]);byte[] buff = new byte[128];int count = -1;while ((count = bis.read(buff)) != -1) {fos.write(buff, 0, count);}bis.close();fos.close();String filename2 = FileUploadUtils.getInstance().uploadImage(tempFile);//調用百度云api上傳文件返回urlschSlide.setName(getFileName(fileFileName[i]));schSlide.setUrl(filename2);schSlide.setStatus(1);schSlide.setSchool(null);schSlideService.addSlide(schSlide); //調用下一層 將url等數據存入數據庫中 }return SUCCESS; } 用到的部分函數/*** 依據原始文件名稱生成新文件名稱* * @return*/private String getName(String fileName) {Random random = new Random();return this.fileName = "" + random.nextInt(10000)+ System.currentTimeMillis() + this.getFileExt(fileName);}/*** 依據字符串創建本地文件夾 并依照日期建立子文件夾返回* * @param path* @return*/private String getFolder(String path) {SimpleDateFormat formater = new SimpleDateFormat("yyyyMMdd");path += "/" + formater.format(new Date());//File dir = new File(this.getPhysicalPath(path));File dir = new File(path);if (!dir.exists()) {try {dir.mkdirs();} catch (Exception e) {//this.state = this.errorInfo.get("DIR");return "";}}return path;}/*** 依據傳入的虛擬路徑獲取物理路徑* * @param path* @return*/private String getPhysicalPath(String path) {String servletPath = this.request.getServletPath();String realPath = this.request.getSession().getServletContext().getRealPath(servletPath);return new File(realPath).getParent() + "/" + path;}//獲取文件名稱稱去掉后綴private String getFileName(String filename){return filename.substring(0, filename.lastIndexOf("."));}
在上傳的過程中文件都是以temp的格式存儲到云中。在網頁瀏覽過程中不能直接獲取。所以我們轉化一下存儲成jsp的格式進行上傳。
FileUploadUtils 類例如以下
package com.hps.util;import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.InputStream;import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory;import com.baidu.inf.iis.bcs.BaiduBCS; import com.baidu.inf.iis.bcs.auth.BCSCredentials; import com.baidu.inf.iis.bcs.auth.BCSSignCondition; import com.baidu.inf.iis.bcs.http.HttpMethodName; import com.baidu.inf.iis.bcs.model.ObjectMetadata; import com.baidu.inf.iis.bcs.request.GenerateUrlRequest; import com.baidu.inf.iis.bcs.request.PutObjectRequest; import com.baidu.inf.iis.bcs.response.BaiduBCSResponse;public class FileUploadUtils {private static FileUploadUtils instance;private static final Log log = LogFactory.getLog(FileUploadUtils.class);// ----------------------------------------//private static String host = "bcs.duapp.com";//accessKey secretKey 自己去申請開發人員賬號自己填寫private static String accessKey = "";private static String secretKey = "";private static String bucket = "";// ---------------------------------------//// ---------------------------------------//private static BCSCredentials credentials = null;private static BaiduBCS baiduBCS = null;// ---------------------------------------////static String object = "/images/first-object2";private static final String IMAGE_DIR = "/images/test/";private static final String FILE_DIR = "/files/";private FileUploadUtils() {credentials = new BCSCredentials(accessKey, secretKey);baiduBCS = new BaiduBCS(credentials, host);baiduBCS.setDefaultEncoding("UTF-8");}public static FileUploadUtils getInstance() {if (instance == null) {instance = new FileUploadUtils();}return instance;}public String uploadImage(File image) {String object = IMAGE_DIR + image.getName();putObjectByFile(image, object);return generateUrl(object);}public static void uploadFile(File file) {String object = FILE_DIR + file.getName();putObjectByFile(file, object);}private static void putObjectByFile(File file, String object) {PutObjectRequest request = new PutObjectRequest(bucket, object, file);ObjectMetadata metadata = new ObjectMetadata();// metadata.setContentType("text/html");request.setMetadata(metadata);BaiduBCSResponse<ObjectMetadata> response = baiduBCS.putObject(request);ObjectMetadata objectMetadata = response.getResult();log.info("x-bs-request-id: " + response.getRequestId());log.info(objectMetadata);}public String generateUrl(String object) {GenerateUrlRequest generateUrlRequest = new GenerateUrlRequest(HttpMethodName.GET, bucket, object);generateUrlRequest.setBcsSignCondition(new BCSSignCondition());//generateUrlRequest.getBcsSignCondition().setIp("115.156.249.55");//generateUrlRequest.getBcsSignCondition().setTime(123455777777L);//generateUrlRequest.getBcsSignCondition().setSize(123455L);return baiduBCS.generateUrl(generateUrlRequest);//上傳百度云的核心}private static File createSampleFile() {//Writer writer = new OutputStreamWriter(new FileOutputStream(file));//URL url = Sample.class.getClassLoader().getResource("20140317172637.jpg");//File file = new File(url.toString());File file = new File("D:\\work\\BAEtest\\WebRoot\\WEB-INF\\classes\\20140317172637.jpg");//file.deleteOnExit();return file;} } 數據庫存數格式例如以下
這樣前臺能夠直接獲取依據url 直接獲取百度云中的圖片非常方便。唯一不足的地方時未來可能會收費。。
。
。
。
寫個文章記錄一下。本人菜鳥,歡迎其這是一個大牛還有問題意見建議。
版權聲明:本文博主原創文章,博客,未經同意不得轉載。
總結
以上是生活随笔為你收集整理的uploadify控制 上传图片到百度云存储的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: iOS UI基础-6.0 UIActio
- 下一篇: SQL Server 2012 Alwa