分享

uploadify 的上传

 走墨 2014-11-14
/**
 * 新增学习资料
 */
var distributeRes;
function addZtxxProjectRes(root,pid){
//top.distributeRoleType.close('distributeRoleType')parent.lhgdialog.list['distributeRoleType']
distributeRes=$.dialog({id:'distributeResId', 
   title:'新增资料',
   background: '#FFF', /* 背景色 默认的遮罩背景色为:#DCE2F1浅蓝护眼色 */ 
   opacity: 0.5,       /* 透明度 */ 
   content: 'url:'+root+'/ztxx/ZtxxProjcetRef/addRes.jsp?pid='+pid+'&date='+new Date().getTime(), 
   max: false, 
   min: false,
   drag: false, 
   resize: false,
   width: 450, 
   height:240
});
}




下面是该页面的内容


<%@page contentType="text/html; charset=UTF-8" %>
<%@ include file="/common/taglibs.jsp"%>

<%@page import="org.my431.util.RandomGuid" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www./TR/xhtml1/DTD/xhtml1-strict.dtd">
<% 
    String myRpath = org.my431.base.services.CacheBasePropertiesManager.getValueByPropertyKey("mysucaiUrl");
    String uploadUrl = org.my431.base.services.CacheBasePropertiesManager.getValueByPropertyKey("uploadUrl");
    String ztxxZlUrl=org.my431.base.services.CacheBasePropertiesManager.getValueByPropertyKey("ztxxZlUrl");
    request.setAttribute("uploadUrl",uploadUrl);
    java.text.SimpleDateFormat sdf1 = new java.text.SimpleDateFormat("yyyyMMdd");
    request.setAttribute("sdfUrl",sdf1.format(new java.util.Date()));
    String ztxxZlUploadUrl=uploadUrl+"/UploadVideo"; //服务器的上传路径
    request.setAttribute("ztxxZlUploadUrl", ztxxZlUploadUrl);
    String zlId=RandomGuid.getUuid();//资料的主键
    request.setAttribute("zlId", zlId);
    String resPath=ztxxZlUrl+"/"+zlId+"/"+sdf1.format(new java.util.Date())+"/"; //上传资源的路径
    request.setAttribute("resPath",resPath);
    request.setAttribute("uploadFileName",resPath);
    request.setAttribute("sessionId", request.getSession().getId());
    String pid=request.getParameter("pid");
    request.setAttribute("pid", pid);
%>

<html xmlns="http://www./1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>主题学习</title>
<meta name="keywords" content="" />
<meta name="description" content="" />
<link href="${portalLoginUrl}/sportal/skins/css/style.css" rel="stylesheet" type="text/css" />
<script src="${root}/skins/ztxx/js/jquery-1.7.1.min.js" type="text/javascript"></script>
<script src="${root}/skins/ztxx/js/all.js" type="text/javascript"></script>
<script src="${root}/ztxx/ztxx.js" type="text/javascript"></script>
<script src="${root}/common/js/lhgdialog/lhgdialog_1.min.js?skin=idialog" type="text/javascript"></script>
<link href="${uploadLoginUrl}/resources/uploadify/css/uploadify.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="${uploadLoginUrl}/resources/uploadify/js/swfobject.js"></script>
<script type="text/javascript" src="${uploadLoginUrl}/resources/uploadify/js/jquery.uploadify.v2.1.0.js"></script>
<style>
.uploadifyQueueItem{
margin-left: 0px;
float: left;
width: 200px;
}
.save{margin-left:30px;}
.save a {
    margin-right:50px;
    float: right;
    margin-right:30px;
   
    line-height: 30px;
    padding: 0px 15px;
    font-size: 14px;
    color: #FFF;
    font-family: "宋体";
    text-decoration: none;
    background: none repeat scroll 0% 0% #4C8C01;
    border-radius: 5px;
}
</style>

<script type="text/javascript">
var isUpload=false;
function change_authimage()//作用??
{
document.all('authimage').src="${root}/common/authimage/authimage.gif?r="+Math.random();
}
function doSubmit()
$("#savep").html("<a href=\"###\"  class=\"btn05\" >保存</a>");
var api = frameElement.api, W = api.opener;
var title=document.getElementById("title");
var memo=document.getElementById("memo");
if (title.value==''){
W.$.dialog.tips('资源名称不能为空!',1,'alert.gif',function(){parent.lhgdialog.list['distributeResId'].zindex();title.focus();});
$("#savep").html("<a href=\"###\" onclick=\"doSubmit();\"  class=\"btn05\" >保存</a>");
return;
}else if (memo.value==''){
W.$.dialog.tips('资源备注不能为空!',1,'alert.gif',function(){parent.lhgdialog.list['distributeResId'].zindex();memo.focus();});
$("#savep").html("<a href=\"###\" onclick=\"doSubmit();\"  class=\"btn05\" >保存</a>");
return;
}else if(isUploadEnd){
$.ajax({
  type: "post",
  url: '${root}/ztxx/ZtxxProjcetRef/saveRef.jspx?pid=${pid}',
  cache:false,
  data:$(document.getElementById('frm')).serialize(),
  dataType:'text',
  error: function(XMLHttpRequest, textStatus, errorThrown) {
       ////alert('Error loading');
   },
  success: function(msg){
  W.location.reload();
  W.$.dialog.tips('新增成功!',1,'alert.gif',function(){});
  W.lhgdialog.list['distributeResId'].close();
          
  }
}); 
}
else
{
W.$.dialog.tips('请选择要上传的资源!',1,'alert.gif',function(){parent.lhgdialog.list['distributeResId'].zindex();});
$("#savep").html("<a href=\"###\" onclick=\"doSubmit();\"  class=\"btn05\" >保存</a>");
}

}

</script>
</head>
<body style="background:#fff">
 <form  action="" method="post"  id="frm" name="frm"  >
 <input type="hidden" name="zlId" id="zlId" value="${zlId}" />
 <input type="hidden" name="fileName" id="fileName"  />
 <input type="hidden" name="fileSize" id="fileSize" />
 <input type="hidden" name="fileExt" id="fileExt" />
 <input type="hidden" name="sourceUrl" id="sourceUrl" />
 <input type="hidden" name="thumbNail" id="thumbNail" value="${thumbNail}" />
 <input type="hidden" name="fileFullName" id="fileFullName" />
<div class="tanBox" style="width: 400px;margin-top: 10px;">
         <ul class="tanBoxul fix">
          <li>
            <label style="width: 80px;">名称:</label>
                <input type="text"  name="title" id="title" class="allInput" maxlength="40" />
                <span >20个汉字以内</span>
            </li>
            <li>
            <label style="width: 80px;">备注:</label>
            <textarea maxlength="200" name="memo" id="memo" ></textarea>
                <span >100个汉字以内</span>
            </li>
            <li>
            <label style="width: 80px;">上传文件:</label>
                <div style="float:left;">
                <div class="choiceFile2 fix" style=" margin:0">
               
            <input type="file" name="uploadify2" id="uploadify2" /> 
            <a id="isUploadedFile" style="text-decoration:none;" target="uploadIframe" ></a>
            </div>
               </div>
            </li>
         </ul>
         <p id="savep"><a href="###"  class="btn05" onclick="doSubmit()" >保存</a></p>
    </div> 
<script type="text/javascript">
//var isUpload=false;
//上传成功调用该函数设置文件信息
function setVideoUrl(info,MyfileObj){
$('#fileSize').val(MyfileObj.size);
$('#fileExt').val(MyfileObj.type);
$('#sourceUrl').val(info);
$('#fileName').val(MyfileObj.name);
$('#isUploadedFile').html(MyfileObj.name);
}
var isUploadEnd = false;//标记上传成功与否
var realFileName;//真是文件名字
var isStart=false;
var scName="";
$(function(){
$("#uploadify2").uploadify({
    'uploader'       : '${uploadLoginUrl}/resources/uploadify/js/uploadify.swf;jsessionid= ${sessionId}',
        'script'         : '${ztxxZlUploadUrl}',//服务器处理上传文件的路径
        'scriptData'     :  {'meetingVedioPath':'${resPath}','uploadFileName':'${uploadFileName}','autoUploadFileName':true,'fullInfo':false,'realFileName':false},//服务器上传文件时需要传给服务器的其他参数
        'cancelImg'      : '${uploadLoginUrl}/resources/uploadify/images/wrong.gif',
        'folder'         : 'uploads',
        'method' : 'GET',
        'auto'           : true,
        'multi'          : false,
        'simUploadLimit' : 1,
        'sizeLimit'      : 50000000,
        'fileDesc' :'请选择文件',
        
        'height'         : 22,   
        'width'          : 55,
        'buttonImg'      : '${portalLoginUrl}/sportal/skins/images/btn09-1.gif', 
        'hideButton'     : false,
        'wmode'          : 'transparent', 
        'onSelect' : function(event, queueId, fileObj)
        {
        $('#isUploadedFile').html('');
        isUploadEnd=false;
        },
'onOpen' :function(event,ID,fileObj){
        isStart=true;
        },         
   'onCancel'      : function(event,data)
        {
    isUploadEnd=true;
    },
        'onComplete'    : function (event, queueID, fileObj, response, data){    
             $.dialog.tips('文件上传成功!',1,'alert.gif',function(){parent.lhgdialog.list['distributeResId'].zindex();setVideoUrl('${resPath}'+response,fileObj);isUploadEnd=true;});
          },    
        'onError'         : function(event, queueID, fileObj, errorObj){ 
                 alert(errorObj.type);
                 $('#uploadify2'+queueID).remove();
                 if(errorObj.type == 'File Size'){
                     $('#isUploadedFile').html('<font color="red">文件过大!只能上传小于50M的文件!</font>');
                 }else{
                  $('#isUploadedFile').html('<font color="red">文件:' + fileObj.name + ' 上传失败!</font>');
                  }
           isUploadEnd=true;
     
     });
var textButton="<input type='text' name='textfield' id='textfield' class='allInput' />  <input type='submit' name='button'  value='浏览' class='type-file-button2' /> "
$(textButton).insertBefore("#fileField");
$("#fileField").change(function(){
var file_upl = document.getElementById('fileField');
var realpath ="";
if (window.navigator.userAgent.indexOf("MSIE") >= 1) { 
file_upl.select();
//realpath= document.selection.createRange().text;
realpath = file_upl.value;
}else
{
realpath = file_upl.value;
}
$("#textfield").val(realpath);});
});
</script>
 </form>
    <iframe src="" id="uploadIframe" name="uploadIframe" style="height: 0px;width: 0px;display:none;"></iframe>
</body>
</html>


下面是uploadServlet


package com.upload.servlet;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
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 com.upload.util.ProcessUtil;
import com.upload.util.RandomGuid;

@SuppressWarnings("serial")
public class Upload extends HttpServlet {
    @SuppressWarnings("unchecked")
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String savePath = this.getServletConfig().getServletContext()
                .getRealPath("");
        String meetingVedioPath=request.getParameter("meetingVedioPath");
        String nFileName=request.getParameter("uploadFileName");
        String autoUploadFileName=request.getParameter("autoUploadFileName");
        String fullInfo = request.getParameter("fullInfo");
        if(nFileName == null || "true".equals(autoUploadFileName)){
        nFileName = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date())+"_"+RandomGuid.getUuid();
        }
        savePath = savePath +"/"+meetingVedioPath;
       
        File f1 = new File(savePath);
        System.out.println(savePath);
        if (!f1.exists()) {
            f1.mkdirs();
        }
        DiskFileItemFactory fac = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(fac);
        upload.setHeaderEncoding("utf-8");
        List fileList = null;
        try {
            fileList = upload.parseRequest(request);
        } catch (FileUploadException ex) {
            return;
        }
        Iterator<FileItem> it = fileList.iterator();
        String realName="";
        String name = "";
        String extName = "";
        long size = 0;
        while (it.hasNext()) {
            FileItem item = it.next();
            if (!item.isFormField()) {
            realName = name = item.getName();
                size = item.getSize();
                String type = item.getContentType();
                System.out.println(size+"字节" + " " + type);
                if (name == null || name.trim().equals("")) {
                    continue;
                }
                //扩展名格式:  
                if (name.lastIndexOf(".") >= 0) {
                    extName = name.substring(name.lastIndexOf("."));
                }
                File file = null;
                do {
                    //生成文件名:
                    name = nFileName;
                    file = new File(savePath + name + extName);
                } while (file.exists());
                File saveFile = new File(savePath + name + extName);
                System.out.println("savepath is " + savePath + name + extName);
                try {
                    item.write(saveFile);
                    if(request.getParameter("ffmpegPath") != null){
                    flvImage(request.getParameter("ffmpegPath"),savePath + name + extName);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        if("true".equals(fullInfo)){
        // 文件全名|文件大小
        if("true".equals(request.getParameter("realFileName"))){
        response.getWriter().print(name + extName+"|"+size+"|"+realName);
        }else{
        response.getWriter().print(name + extName+"|"+size);
        }
        }else{
        response.getWriter().print(name + extName);
        }
    }
    
    private static boolean flvImage(String commandPath, String flvFile) {
    //String uploadPath=My431Function.getValueByCode("ffmpeg.url").trim();
    String imgFile = flvFile.substring(0,flvFile.lastIndexOf("."))+"_img.jpg";
    String avitoflv=commandPath+" -i "+flvFile+" -ss 2 -vframes 1 -r 1 -ac 1 -ab 2 -s 600*410 -f  image2 "+imgFile;
    boolean flag1=false;
    try {
    int flag=ProcessUtil.execProcess(avitoflv);
    if (flag==0){
    System.out.println("ffmpeg trans flv the transfer is ok!");
    flag1=true;
    }else{
    flag1=false;
    }
    } catch (Throwable e) {     
    //e.printStackTrace();     
    }
    return flag1;
}
    
    
}


    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约