zoukankan      html  css  js  c++  java
  • 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";
    	
    	@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;
    	}
    }
    
    数据库存数格式例如以下





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




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



    版权声明:本文博主原创文章,博客,未经同意不得转载。

  • 相关阅读:
    第二次编程作业总结
    structs get 方法乱码问题
    网址记录
    尸体解剖报告
    最后冲刺
    回答自己的提问——对自己最大的反馈
    构建之法13-17章读后感
    典型场景
    对其他各团队的评价
    用户调研
  • 原文地址:https://www.cnblogs.com/blfshiye/p/4806587.html
Copyright © 2011-2022 走看看