java-uploadify 批量上传文件到七牛云

8 篇文章 0 订阅
4 篇文章 0 订阅
  1.  搭建一个简单的SpringMVC框架
  2. 需要的jar包:
          1. okhttp-3.2.0.jar
          2. okio-1.9.0.jar
          3.qiniu-java-sdk-7.2.7.jar
          下载地址:
          链接:http://pan.baidu.com/s/1o7IWMh0 密码:73fk
  1. 前端需要的资源:
          1.uploadify.css
          2.jquery-1.4.2.min.js
          3.jquery.uploadify.min.js
          4.uploadify.swf
          5.cancel.png
          下载地址:
          链接:http://pan.baidu.com/s/1c2w6KKC 密码:g607
  1. 上传页面编写:index.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 > jquery upload </ title >
     < link  rel = "stylesheet"  href = "uploadify/uploadify.css"  type = "text/css" ></ link >  
     < script  type = "text/javascript"  src = "js/jquery-1.4.2.min.js" ></ script >
     < script  type = "text/javascript"  src = "uploadify/jquery.uploadify.min.js" ></ script >
     < script  type = "text/javascript" >
        $( function  () {
            $( "#file_upload" ).uploadify({
                 //指定swf文件
                'swf' :  'uploadify/uploadify.swf' ,
                 //后台处理的页面
                'uploader' :  'upload/testQiNiu.do' ,
                 'progressData'  :  'speed' ,
                 //按钮显示的文字
                'buttonText' :  '上传文件' ,
                 //显示的高度和宽度,默认 height 30;width 120
                 //'height': 15,
                 //'width': 80,
                 //上传文件的类型  默认为所有文件    'All Files'  ;  '*.*'
                 //在浏览窗口底部的文件类型下拉菜单中显示的文本
                'fileTypeDesc' :  'All Files' ,
                 //允许上传的文件后缀
                 //'fileTypeExts': '*.gif; *.jpg; *.png',
                'cancel' :  'uploadify/cancel.png' ,
                 //上传文件页面中,你想要用来作为文件队列的元素的id, 默认为false  自动生成,  不带#
                'queueID' :  'fileQueue' ,
                 //选择文件后自动上传
                'auto' :  false ,
                 //设置为true将允许多文件上传
                'multi' :  true ,
                 /* 'onUploadComplete' : function(file) {
                     alert('上传完成');
                 }, */
                'onCancel'  :  function (file) {
                     alert( '取消上传' );
                 }
            });
        });
     </ script >
   </ head >
   < body >
     < div  id = "fileQueue" ></ div >  
     < input  type = "file"  name = "file_upload"  id = "file_upload"  />
     < p >  
         < a  href = "javascript:$('#file_upload').uploadify('upload','*')" > 开始上传 </ a >   
         < a  href = "javascript:$('#uploadify').uploadify('cancel')" > 取消所有上传 </ a >  
     </ p >  
   </ body >
</ html >


  1. 工具类编写:IPTimeStamp.java
          利用客户端IP+时间+三位随机数字生成非重复文件名
          
package  com.qiang;
//PTimeStamp.java
import  java.net.InetAddress;
import  java.net.UnknownHostException;
import  java.text.SimpleDateFormat;
import  java.util.Date;
import  java.util.Random;
public  class  IPTimeStamp {
      private  String  ip ;
      private  Date  date ;
      private  SimpleDateFormat  format ;
      public  IPTimeStamp() {
            try  {
                 ip  = InetAddress.getLocalHost().getHostAddress();
           }  catch  (UnknownHostException e) {
                 //  TODO  Auto-generated catch block
                e.printStackTrace();
           }
     }
      public  String getTimeStamp() {
            format  =  new  SimpleDateFormat( "yyyyMMddHHmmssSSS" );
            return  format .format( new  Date());
     }
      public  String addZero(String str,  int  len) {
           StringBuffer sb =  new  StringBuffer();
           sb.append(str);
            while  (sb.length() < len) {
                sb.insert(0,  "0" );
           }
            return  sb.toString();
     }
      public  String getIPTimeStampRandom() {
           StringBuffer sb =  new  StringBuffer();
           String[] ips =  this . ip .split( "\\." );
            for  ( int  j = 0; j < ips. length ; j++) {
                 // System.out.println(ips[j]);
                sb.append( this .addZero(ips[j], 3));
           }
           sb.append( this .getTimeStamp());
           Random rod =  new  Random();
            for  ( int  i = 0; i < 3; i++) {
                sb.append(rod.nextInt(10));
           }
            return  sb.toString();
     }
}
  1. 文件上传控制器编写:UploadController.java
package  com.qiang;
import  java.io.File;
import  java.io.IOException;
import  java.util.Iterator;
import  java.util.List;
import  javax.servlet.http.HttpServletRequest;
import  javax.servlet.http.HttpServletResponse;
import  org.apache.commons.fileupload.FileItem;
import  org.apache.commons.fileupload.FileUploadException;
import  org.apache.commons.fileupload.disk.DiskFileItemFactory;
import  org.apache.commons.fileupload.servlet.ServletFileUpload;
import  org.springframework.stereotype.Controller;
import  org.springframework.web.bind.annotation.RequestMapping;
import  com.qiniu.http.Response;
import  com.qiniu.storage.Configuration;
import  com.qiniu.storage.UploadManager;
import  com.qiniu.util.Auth;
@Controller
@RequestMapping ( "/upload" )
public  class  UploadController {
      //设置好账号的ACCESS_KEY和SECRET_KEY
       String  ACCESS_KEY  =  "Le8jyHg71J7UuV***KYUmF-UMbJOZgmLMO" ;  //这两个登录七牛 账号里面可以找到
       String  SECRET_KEY  =  "VMO5cIW***ifokRkefGE_WWxKmC2n2d" ;
        //要上传的空间
       String  bucketname  =  "usercenterfilesccw" ;  //对应要上传到七牛上 你的那个路径(自己建文件夹 注意设置公开)
        //上传到七牛后保存的文件名
       String  key  =  "test.doc"
        //密钥配置
       Auth  auth  = Auth.create( ACCESS_KEY ,  SECRET_KEY );
        //创建上传对象
       Configuration  conf = new  Configuration();
      
       UploadManager  uploadManager ;
       {
              uploadManager = new  UploadManager( conf );
       }
      /**上传到本地服务器
      *  @param  request
      *  @param  response
      */
      @RequestMapping ( "/test.do" )
      public  void  test(HttpServletRequest request,HttpServletResponse response){
           String savePath = request.getSession().getServletContext()
                .getRealPath( "" );
            // 得到项目的工作目录
           savePath = savePath +  "/uploads/" ;
           File f1 =  new  File(savePath);
            // 如果没有的话就创建目录
            if  (!f1.exists()) {
                f1.mkdirs();
           }
           DiskFileItemFactory fac =  new  DiskFileItemFactory();
           ServletFileUpload upload =  new  ServletFileUpload(fac);
           upload.setHeaderEncoding( "utf-8" );
           List<FileItem> fileList =  null ;
            try  {
                fileList = upload.parseRequest(request);
           }  catch  (FileUploadException ex) {
                 return ;
           }
           Iterator<FileItem> it = fileList.iterator();
           String name =  "" ;
           String extName =  "" ;
            while  (it.hasNext()) {
                FileItem item = it.next();
                 if  (!item.isFormField()) {
                      // 解析文件
                     name = item.getName();
                      long  size = item.getSize();
                     String type = item.getContentType();
                      if  (name ==  null  || name.trim().equals( "" )) {
                            continue ;
                     }
                      // 得到文件的扩展名
                      if  (name.lastIndexOf( "." ) >= 0) {
                           extName = name.substring(name.lastIndexOf( "." ));
                     }
                     File file =  null ;
                      do  {
                            // 利用客户端IP+时间+三位随机数字生成非重复文件名:
                           name =  new  IPTimeStamp().getIPTimeStampRandom();
                           file =  new  File(savePath + name + extName);
                     }  while  (file.exists());
                     File saveFile =  new  File(savePath + name + extName);
                      try  {
                           item.write(saveFile);
                     }  catch  (Exception e) {
                           e.printStackTrace();
                     }
                }
           }
            try  {
                response.getWriter().print(name + extName);
           }  catch  (IOException e) {
                e.printStackTrace();
           }
           
     }
      /**上传到七牛云端
      *  @param  request
      *  @param  response
      */
      @RequestMapping ( "testQiNiu.do" )
      public  void  testQN(HttpServletRequest request,HttpServletResponse response){
           List<FileItem> fileList =  null ;
            try  {
                DiskFileItemFactory fac =  new  DiskFileItemFactory();
                ServletFileUpload upload =  new  ServletFileUpload(fac);
                fileList = upload.parseRequest(request);
           }  catch  (FileUploadException ex) {
                 return ;
           }
           Iterator<FileItem> it = fileList.iterator();
            try  {
                 while  (it.hasNext()) {
                     FileItem item = it.next();
                           Response res =  uploadManager .put(item.getInputStream(),  key , getUpToken(), null ,  "application/zip" );
                System. out .println(res.getInfo());
                }
           }  catch  (Exception e) {
                e.printStackTrace();
           }
     }
     
        //简单上传,使用默认策略,只需要设置上传的空间名就可以了
        public  String getUpToken(){
            return  auth .uploadToken( bucketname );
       }
}

demo已上传至GitHub,地址如下:
https://github.com/18394093929/QiNiuBatchFileUpload

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值