码迷,mamicode.com
首页 > 其他好文 > 详细

uploadify控件 上传图片到百度云存储

时间:2014-05-15 06:29:33      阅读:369      评论:0      收藏:0      [点我收藏+]

标签:uploadify   百度云存储   百度云   

最近使用了uploadify 控件上传图片到百度云。。。。大体思路是 前台通过uploadify获取文件传入后台,调用百度云存储api上传到百度云,返回一个url 链接。我们把链接存储到数据库中,这样我们数据库中就是只有url  而真正的文件保存在百度云存储当中,很轻便很好用。这一个业务流程用到了uploadify 控件和百度云存储。

流程如下:首先下载uploadify 包

bubuko.com,布布扣

bubuko.com,布布扣

这个不同文件混在一起还没有分开。。功能先实现再说。。。

前台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,用于打开选取本地文件的按钮 
                ‘script‘         : ‘uploadify.php‘,
                ‘fileObjName‘    :  ‘file‘,
                ‘cancelImg‘      : ‘uploadify/uploadify-cancel.png‘,//取消上传文件的按钮图片,就是个叉叉                
                ‘folder‘         : ‘uploadify/uploads‘,//上传文件的目录
                ‘queueID‘        : ‘fileQueue‘,
                ‘auto‘           : false,//是否选取文件后自动上传
                ‘multi‘          : true,//是否支持多文件上传
                ‘simUploadLimit‘ : 7,//每次最大上传文件数
                ‘buttonText‘     : ‘选择文件‘,//按钮上的文字
                ‘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";
	
	@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的格式进行上传。

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;
	}
}
数据库存数格式如下

bubuko.com,布布扣



这样前台可以直接获取根据url 直接获取百度云中的图片很方便。唯一不足的地方时未来可能会收费。。。。。


写个文章记录一下,本人菜鸟,欢迎其他大牛提建议意见还有问题。


uploadify控件 上传图片到百度云存储,布布扣,bubuko.com

uploadify控件 上传图片到百度云存储

标签:uploadify   百度云存储   百度云   

原文地址:http://blog.csdn.net/captain_wl9083/article/details/25695415

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!