最近使用uploadify 控制圖片上傳到百度網盤。。。。總的想法是 招待會uploadify獲取文件傳入後臺,調用百度雲存儲api上傳到百度網盤,返回url 聯繫。送存儲在數據庫中的連接。所以,咱們有一個數據庫,這只是url 真正的文件保存在百度雲存儲這,常好用。這一個業務流程用到了uploadify 控件和百度雲存儲。javascript
流程例如如下:首先下載uploadify 包php
這個不一樣文件混在一塊兒尚未分開。css
。功能先實現再說。。。html
前臺jsp頁面例如如下:java
<%@ 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>
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";
@Autowired
private 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上傳文件返回url
schSlide.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的格式進行上傳。jquery
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 直接獲取百度雲中的圖片很是方便。惟一不足的地方時將來可能會收費。。apache
。json
。api
。 寫個文章記錄一下。本人菜鳥,歡迎其這是一個大牛還有問題意見建議。