利用commons upload+ffmpeg+mencoder完成视频的上传与转换

     前一段时间朱哥一直在搞视频转换这个东东,我也一直很有兴趣,就尝试了一下。

     首先是文件上传功能的完成,做得很粗糙,没有验证上传文件是否为视频文件。利用前一段时间看视频学来的部分代码很轻松搞定。

     接下来,就是视频转换了,我的ffmpeg和mencoder放在d:\ffmpeg目录中,代码如下

ContractedBlock.gif ExpandedBlockStart.gif Code
<!--<br /><br />Code highlighting produced by Actipro CodeHighlighter (freeware)<br />http://www.CodeHighlighter.com/<br /><br />-->package com.lc.test;

import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

public class CodeConven {

    
private static String OldPath;
    
private static String NewPath;


    
public static boolean process() {
    
int type = checkContentType();
    
boolean status = false;
    
if (type == 0) {
        status 
= processFLV(OldPath);// 直接将文件转为flv文件
    } else if (type == 1) {
        String avifilepath 
= processAVI(type);
        
if (avifilepath == null)
        
return false;// avi文件没有得到
        status = processFLV(avifilepath);// 将avi转为flv
    }
    
return status;
    }

    
private static int checkContentType() {
    String type 
= OldPath.substring(OldPath.lastIndexOf("."+ 1,
        OldPath.length()).toLowerCase();
    
// ffmpeg能解析的格式:(asx,asf,mpg,wmv,3gp,mp4,mov,avi,flv等)
    if (type.equals("avi")) {
        
return 0;
    } 
else if (type.equals("mpg")) {
        
return 0;
    } 
else if (type.equals("wmv")) {
        
return 0;
    } 
else if (type.equals("3gp")) {
        
return 0;
    } 
else if (type.equals("mov")) {
        
return 0;
    } 
else if (type.equals("mp4")) {
        
return 0;
    } 
else if (type.equals("asf")) {
        
return 0;
    } 
else if (type.equals("asx")) {
        
return 0;
    } 
else if (type.equals("flv")) {
        
return 0;
    }
    
// 对ffmpeg无法解析的文件格式(wmv9,rm,rmvb等),
    
// 可以先用别的工具(mencoder)转换为avi(ffmpeg能解析的)格式.
    else if (type.equals("wmv9")) {
        
return 1;
    } 
else if (type.equals("rm")) {
        
return 1;
    } 
else if (type.equals("rmvb")) {
        
return 1;
    }
    
return 9;
    }

    
private static boolean checkfile(String OldPath) {
    File file 
= new File(OldPath);
    
if (!file.isFile()) {
        
return false;
    }
    
return true;
    }

    
// 对ffmpeg无法解析的文件格式(wmv9,rm,rmvb等), 可以先用别的工具(mencoder)转换为avi(ffmpeg能解析的)格式.
    private static String processAVI(int type) {
    List
<String> commend = new java.util.ArrayList<String>();
    commend.add(
"d:\\ffmpeg\\mencoder");
    commend.add(OldPath);
    commend.add(
"-oac");
    commend.add(
"lavc");
    commend.add(
"-lavcopts");
    commend.add(
"acodec=mp3:abitrate=64");
    commend.add(
"-ovc");
    commend.add(
"xvid");
    commend.add(
"-xvidencopts");
    commend.add(
"bitrate=600");
    commend.add(
"-of");
    commend.add(
"avi");
    commend.add(
"-o");
    commend.add(NewPath);
    
try {
        ProcessBuilder builder 
= new ProcessBuilder();
        builder.command(commend);
        builder.start();
        
return NewPath;
    } 
catch (Exception e) {
        e.printStackTrace();
        
return null;
    }
    }

    
// ffmpeg能解析的格式:(asx,asf,mpg,wmv,3gp,mp4,mov,avi,flv等)
    private static boolean processFLV(String oldfilepath) {

    
if (!checkfile(OldPath)) {
        System.out.println(oldfilepath 
+ " is not file");
        
return false;
    }

    List
<String> commend = new java.util.ArrayList<String>();
    commend.add(
"d:\\ffmpeg\\ffmpeg");
    commend.add(
"-i");
    commend.add(oldfilepath);
    commend.add(
"-y");
    commend.add(
"-ab");
    commend.add(
"32");
    commend.add(
"-ar");
    commend.add(
"22050");
    commend.add(
"-b");
    commend.add(
"800000");
    commend.add(
"-s");
    commend.add(
"640*480");
    commend.add(NewPath);
    
try {
        ProcessBuilder builder 
= new ProcessBuilder();
        builder.command(commend);
        builder.start();
        
return true;
    } 
catch (Exception e) {
        e.printStackTrace();
        
return false;
    }
    }

    
public String getOldPath() {
    
return OldPath;
    }

    
public void setOldPath(String oldPath) {
    OldPath 
= oldPath;
    }

    
public String getNewPath() {
    
return NewPath;
    }

    
public void setNewPath(String newPath) {
    NewPath 
= newPath;
    }
}

 

     写个测试类试了一下,挺好使的,转换的速度也还行。

     接下来就是要在上传类上略作修改,把转换的步骤加进去就ok了。

     以下是添加视频转换功能后的上传类代码:

ContractedBlock.gif ExpandedBlockStart.gif Code
<!--<br /><br />Code highlighting produced by Actipro CodeHighlighter (freeware)<br />http://www.CodeHighlighter.com/<br /><br />-->package com.lc.test;

import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
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.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

public class UploadServlet extends HttpServlet {

    
private static final long serialVersionUID = 2431664260164700200L;
    
private ServletContext sc;
    
private String savePath;

    
/**
     * The doGet method of the servlet. <br>
     * 
     * This method is called when a form has its tag value method equals to get.
     * 
     * 
@param request
     *            the request send by the client to the server
     * 
@param response
     *            the response send by the server to the client
     * 
@throws ServletException
     *             if an error occurred
     * 
@throws IOException
     *             if an error occurred
     
*/
    
public void doGet(HttpServletRequest request, HttpServletResponse response)
            
throws ServletException, IOException {
        doPost(request, response);
    }

    
/**
     * The doPost method of the servlet. <br>
     * 
     * This method is called when a form has its tag value method equals to
     * post.
     * 
     * 
@param request
     *            the request send by the client to the server
     * 
@param response
     *            the response send by the server to the client
     * 
@throws ServletException
     *             if an error occurred
     * 
@throws IOException
     *             if an error occurred
     
*/
    
public void doPost(HttpServletRequest request, HttpServletResponse response)
            
throws ServletException, IOException {
        request.setCharacterEncoding(
"UTF-8");

        DiskFileItemFactory factory 
= new DiskFileItemFactory();
        ServletFileUpload upload 
= new ServletFileUpload(factory);

        
try {
            List items 
= upload.parseRequest(request);
            Iterator it 
= items.iterator();
            
while (it.hasNext()) {
                FileItem item 
= (FileItem) it.next();
                
if (item.isFormField()) {
                    System.out.println(
"表单的参数名称:" + item.getFieldName()
                            
+ ",对应的参数值:" + item.getString("UTF-8"));
                } 
else {
                    
if (item.getName() != null && !item.getName().equals("")) {
                        System.out.println(
"上传文件的大小:" + item.getSize());
                        System.out.println(
"上传文件的类型:" + item.getContentType());
                        System.out.println(
"上传文件的名称:" + item.getName());

                        File tempFile 
= new File(item.getName());
                        File file 
= new File(sc.getRealPath("/"+ savePath,
                                tempFile.getName());
                        item.write(file);
//                        System.out.println(sc.getRealPath("/") + savePath);
//                        request.setAttribute("upload.message", "上传文件成功!");
                        CodeConven cc= new CodeConven();
                        String oldfilename
=item.getName().substring(item.getName().lastIndexOf("\\")+1,item.getName().length()).toLowerCase();
                        String newfilename
=oldfilename.substring(0,oldfilename.lastIndexOf("."))+".flv";
                        String oldPath
=sc.getRealPath("/"+ savePath+"\\"+oldfilename;
                        String newPath
=sc.getRealPath("/"+"output\\"+newfilename;
//                        System.out.println("文件名:"+item.getName());
//                        System.out.println("原路径:"+oldPath);
//                        System.out.println("转换后路径:"+newPath);
                        cc.setOldPath(oldPath);
                        cc.setNewPath(newPath);
                        
if(cc.process()){
                            System.out.println(
"conven ok");
                        }

                    } 
else {
                        request.setAttribute(
"upload.message""没有选择上传文件!");
                    }
                }
                
            }
        } 
catch (Exception e) {
            e.printStackTrace();
            request.setAttribute(
"upload.message""上传文件不成功!");
        }
        
       request.getRequestDispatcher(
"/uploadResult.jsp").forward(request, response);
    }

    
public void init(ServletConfig config) {
        savePath 
= config.getInitParameter("savePath");
        sc 
= config.getServletContext();

    }

}

 

     ok了,写这个主要是为了实现,具体有其他不到位的地方还请大家指正啊。

 

源码下载

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值