JAVA上传图片/视频等文件

目前已测上传支持格式:{".rar", ".doc", ".docx", ".zip",
            ".pdf", ".txt", ".swf", ".xlsx", ".gif", ".png", ".jpg", ".jpeg",
            ".bmp", ".xls", ".mp4", ".flv", ".ppt", ".avi", ".mpg", ".wmv",
            ".3gp", ".mov", ".asf", ".asx", ".vob", ".wmv9", ".rm", ".rmvb"{

允许视频转码的格式:{ ".wmv9", ".rm", ".rmvb" }

如需上传多文件,后台需要使用MultipartFile[] 数组接收,然后for循环fileUploadTool.createFile,多文件上传未做测试,有需要的小伙伴自行测试。

1,前端代码

function testUploadVideo(){
	var fileObj = document.getElementById("file").files[0];  //获取文件对象
	var formFile = new FormData();
	formFile.append("param", "100");  //传入需要传的参数
	formFile.append("file", fileObj); // 加入文件对象
	var data = formFile;
	
	$.ajax({
		url : "../../lecture/uploadflv/uploadSave.action",
		type : "post",
		data : data,
		cache : false,// 上传文件无需缓存
		processData : false,// 用于对data参数进行序列化处理 这里必须false
		contentType : false, // 必须
		success : function(res) {
			alert("生成成功");
			alert(JSON.parse(res).result);  //接收前台返回json字符串
		},
		error : function() {
			alert("生成失败");
		}
	})
}
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<!-- <html xmlns="http://www.w3.org/1999/xhtml"> -->
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="utf-8">
	<meta http-equiv="Content-Type" content="text/html" />
	<meta name="viewport"
		content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no" />
	<script src="../js/jquery.min.js"></script>
	<script type="text/javascript" src="../js/jquery.touchSwipe.min.js"></script>
	<link rel="stylesheet" href="../css/indexpage.css">
		<script  src="/lecture/html/indexpage/indexpage.js"></script>
		<title>视频图片测试页</title>
</head>
<body>




            <form class="" id="upload" method="post" enctype="multipart/form-data">
                <div >
                    <input type="file" class="form-control" name="file" id="file"><br>
                    <!-- <button id="testUploadVideo" type="button" onclick="testUploadVideo()">上传but</button> -->
                    <a id="testUploadVideo" onclick="testUploadVideo()" >上传</a>
                   
                </div>
            </form>

    
	
</body>
</html>

 

2,控制器

package com.ejfee.tw.twweb.videoupload.controller;

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

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSON;
import com.ejfee.tw.twweb.videoupload.domain.FileEntity;
import com.ejfee.tw.twweb.videoupload.util.FileUploadTool;

@Controller
@RequestMapping("uploadflv")
public class UploadController {

	@RequestMapping(value = "uploadSave", method = RequestMethod.POST)
	@ResponseBody
	public void upload(@RequestParam(value = "file", required = false) MultipartFile multipartFile, HttpServletRequest request,
			HttpServletResponse response, ModelMap map,String param) {
		response.setContentType("text/html;charset=UTF-8"); //设置返回值编码格式
		String a = request.getParameter("param");
		String message = "";
		FileEntity entity = new FileEntity();
		FileUploadTool fileUploadTool = new FileUploadTool();
		try {
			entity = fileUploadTool.createFile(multipartFile, request);
			if (entity != null) {
				// service.saveFile(entity); //将视频上传路径,视频名称,视频时长等内容保存至数据库
				message = "SUCCESS";
				map.put("entity", entity);
				map.put("result", message);
			} else {
				message = "FAIL";
				map.put("result", message);
			}
			response.getWriter().write(JSON.toJSONString(map));
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
}

 

3,实体类

package com.ejfee.tw.twweb.videoupload.domain;
import java.sql.Timestamp;

public class FileEntity {
    private String type;
    private String size;
    private String path;
    private String titleOrig;
    private String titleAlter;
    private Timestamp uploadTime;
    public String getType() {
        return type;
    }
    public void setType(String type) {
        this.type = type;
    }
    public String getSize() {
        return size;
    }
    public void setSize(String size) {
        this.size = size;
    }
    public String getPath() {
        return path;
    }
    public void setPath(String path) {
        this.path = path;
    }
    public String getTitleOrig() {
        return titleOrig;
    }
    public void setTitleOrig(String titleOrig) {
        this.titleOrig = titleOrig;
    }
    public String getTitleAlter() {
        return titleAlter;
    }
    public void setTitleAlter(String titleAlter) {
        this.titleAlter = titleAlter;
    }
    public Timestamp getUploadTime() {
        return uploadTime;
    }
    public void setUploadTime(Timestamp uploadTime) {
        this.uploadTime = uploadTime;
    }
}

4,util 方法类

package com.ejfee.tw.twweb.videoupload.util;
import java.io.File;
import java.io.IOException;
import java.sql.Timestamp;
import java.text.DecimalFormat;
import java.util.Arrays;
import java.util.Iterator;

import javax.servlet.http.HttpServletRequest;

import org.springframework.web.multipart.MultipartFile;

import com.ejfee.tw.twweb.videoupload.domain.FileEntity;

public class FileUploadTool {

    TransfMediaTool transfMediaTool = new TransfMediaTool();
    // 文件最大500M
    private static long upload_maxsize = 800 * 1024 * 1024;
    // 文件允许格式
    private static String[] allowFiles = { ".rar", ".doc", ".docx", ".zip",
            ".pdf", ".txt", ".swf", ".xlsx", ".gif", ".png", ".jpg", ".jpeg",
            ".bmp", ".xls", ".mp4", ".flv", ".ppt", ".avi", ".mpg", ".wmv",
            ".3gp", ".mov", ".asf", ".asx", ".vob", ".wmv9", ".rm", ".rmvb" };
    // 允许转码的视频格式(ffmpeg)
    private static String[] allowFLV = { ".avi", ".mpg", ".wmv", ".3gp",
            ".mov", ".asf", ".asx", ".vob" };
    // 允许的视频转码格式(mencoder)
    private static String[] allowAVI = { ".wmv9", ".rm", ".rmvb" };

    public FileEntity createFile(MultipartFile multipartFile, HttpServletRequest request) {
        FileEntity entity = new FileEntity();
        boolean bflag = false;
        String fileName = multipartFile.getOriginalFilename().toString();
        // 判断文件不为空
        if (multipartFile.getSize() != 0 && !multipartFile.isEmpty()) {
            bflag = true;
            // 判断文件大小
            if (multipartFile.getSize() <= upload_maxsize) {
                bflag = true;
                // 文件类型判断
                if (this.checkFileType(fileName)) {
                    bflag = true;
                } else {
                    bflag = false;
                    System.out.println("文件类型错误");
                }
            } else {
                bflag = false;
                System.out.println("文件大小超范围");
            }
        } else {
            bflag = false;
            System.out.println("文件为空");
        }
        if (bflag) {
            String logoPathDir = "/video/";
            // 上传到本地磁盘
            // String logoRealPathDir = "E:/upload";
            // request.getServletContext().getRealPath("/")
            // String logoRealPathDir = request.getSession().getServletContext().getRealPath("/videoAndImage/video");
            String logoRealPathDir = "E:/upload";
            
            File logoSaveFile = new File(logoRealPathDir);
            if (!logoSaveFile.exists()) {
                logoSaveFile.mkdirs();
            }
            String name = fileName.substring(0, fileName.lastIndexOf("."));
            System.out.println("文件名称:" + name);
            // 新的文件名
            String newFileName = this.getName(fileName);
            // 文件扩展名
            String fileEnd = this.getFileExt(fileName);
            // 绝对路径
            String fileNamedirs = logoRealPathDir + File.separator + newFileName + fileEnd;
            System.out.println("保存的绝对路径:" + fileNamedirs);
            File filedirs = new File(fileNamedirs);
            // 转入文件
            try {
                multipartFile.transferTo(filedirs);
            } catch (IllegalStateException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            // 相对路径
            entity.setType(fileEnd);
            String fileDir = logoPathDir + newFileName + fileEnd;
            StringBuilder builder = new StringBuilder(fileDir);
            String finalFileDir = builder.substring(1);
            // size存储为String
            String size = this.getSize(filedirs);
            // 源文件保存路径
            String aviPath = filedirs.getAbsolutePath();
            // 转码Avi
//            boolean flag = false;
            if (this.checkAVIType(fileEnd)) {
                // 设置转换为AVI格式后文件的保存路径
                String codcAviPath = logoRealPathDir + File.separator + newFileName + ".avi";
                // 获取配置的转换工具(mencoder.exe)的存放路径
                String mencoderPath = request.getSession().getServletContext().getRealPath("/tools/mencoder.exe");
                aviPath = transfMediaTool.processAVI(mencoderPath, filedirs.getAbsolutePath(), codcAviPath);
                fileEnd = this.getFileExt(codcAviPath);
            }
            if (aviPath != null) {
                // 转码Flv
                if (this.checkMediaType(fileEnd)) {
                    try {
                        // 设置转换为flv格式后文件的保存路径
                        String codcFilePath = logoRealPathDir + File.separator + newFileName + ".flv";
                        // 获取配置的转换工具(ffmpeg.exe)的存放路径
                        String ffmpegPath = request.getSession().getServletContext().getRealPath("/tools/ffmpeg.exe");
                        transfMediaTool.processFLV(ffmpegPath, aviPath,    codcFilePath);
                        fileDir = logoPathDir + newFileName + ".flv";
                        builder = new StringBuilder(fileDir);
                        finalFileDir = builder.substring(1);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                entity.setSize(size);
                entity.setPath(finalFileDir);
                entity.setTitleOrig(name);
                entity.setTitleAlter(newFileName);
                Timestamp timestamp = new Timestamp(System.currentTimeMillis());
                entity.setUploadTime(timestamp);
                //可以再此处将视频上传路径,视频名称,视频时长等内容保存至数据库
                return entity;
            } else {
                return null;
            }
        } else {
            return null;
        }

    }

    /**
     * 文件类型判断
     *
     * @param fileName
     * @return
     */
    private boolean checkFileType(String fileName) {
        Iterator<String> type = Arrays.asList(allowFiles).iterator();
        while (type.hasNext()) {
            String ext = type.next();
            if (fileName.toLowerCase().endsWith(ext)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 视频类型判断(flv)
     *
     * @param fileName
     * @return
     */
    private boolean checkMediaType(String fileEnd) {
        Iterator<String> type = Arrays.asList(allowFLV).iterator();
        while (type.hasNext()) {
            String ext = type.next();
            if (fileEnd.equals(ext)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 视频类型判断(AVI)
     *
     * @param fileName
     * @return
     */
    private boolean checkAVIType(String fileEnd) {
        Iterator<String> type = Arrays.asList(allowAVI).iterator();
        while (type.hasNext()) {
            String ext = type.next();
            if (fileEnd.equals(ext)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 获取文件扩展名
     *
     * @return string
     */
    private String getFileExt(String fileName) {
        return fileName.substring(fileName.lastIndexOf("."));
    }

    /**
     * 依据原始文件名生成新文件名
     * @return
     */
    private String getName(String fileName) {
        Iterator<String> type = Arrays.asList(allowFiles).iterator();
        while (type.hasNext()) {
            String ext = type.next();
            if (fileName.contains(ext)) {
                String newFileName = fileName.substring(0, fileName.lastIndexOf(ext));
                return newFileName;
            }
        }
        return "";
    }

    /**
     * 文件大小,返回kb.mb
     *
     * @return
     */
    private String getSize(File file) {
        String size = "";
        long fileLength = file.length();
        DecimalFormat df = new DecimalFormat("#.00");
        if (fileLength < 1024) {
            size = df.format((double) fileLength) + "BT";
        } else if (fileLength < 1048576) {
            size = df.format((double) fileLength / 1024) + "KB";
        } else if (fileLength < 1073741824) {
            size = df.format((double) fileLength / 1048576) + "MB";
        } else {
            size = df.format((double) fileLength / 1073741824) + "GB";
        }
        return size;
    }
}
package com.ejfee.tw.twweb.videoupload.util;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

public class TransfMediaTool {
    
    /**
     * 视频转码flv
     *
     * @param ffmpegPath
     *            转码工具的存放路径
     * @param upFilePath
     *            用于指定要转换格式的文件,要截图的视频源文件
     * @param codcFilePath
     *            格式转换后的的文件保存路径
     * @return
     * @throws Exception
     */
    public void processFLV(String ffmpegPath, String upFilePath, String codcFilePath) {
        // 创建一个List集合来保存转换视频文件为flv格式的命令
        List<String> convert = new ArrayList<String>();
        convert.add(ffmpegPath); // 添加转换工具路径
        convert.add("-i"); // 添加参数"-i",该参数指定要转换的文件
        convert.add(upFilePath); // 添加要转换格式的视频文件的路径
        convert.add("-ab");
        convert.add("56");
        convert.add("-ar");
        convert.add("22050");
        convert.add("-q:a");
        convert.add("8");
        convert.add("-r");
        convert.add("15");
        convert.add("-s");
        convert.add("600*500");

        /*
         * convert.add("-qscale"); // 指定转换的质量 convert.add("6");
         * convert.add("-ab"); // 设置音频码率 convert.add("64"); convert.add("-ac");
         * // 设置声道数 convert.add("2"); convert.add("-ar"); // 设置声音的采样频率
         * convert.add("22050"); convert.add("-r"); // 设置帧频 convert.add("24");
         * convert.add("-y"); // 添加参数"-y",该参数指定将覆盖已存在的文件
         */
        convert.add(codcFilePath);
        try {
            Process videoProcess = new ProcessBuilder(convert).redirectErrorStream(true).start();
            new PrintStream(videoProcess.getInputStream()).start();
            videoProcess.waitFor();
        } catch (IOException e1) {
            e1.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    /**
     * 对ffmpeg无法解析的文件格式(wmv9,rm,rmvb等), 先用mencoder转换为avi(ffmpeg能解析的)格式
     *
     * @param mencoderPath
     *            转码工具的存放路径
     * @param upFilePath
     *            用于指定要转换格式的文件,要截图的视频源文件
     * @param codcFilePath
     *            格式转换后的的文件保存路径
     * @return
     * @throws Exception
     */
    public String processAVI(String mencoderPath, String upFilePath, String codcAviPath) {
//        boolean flag = false;
        List<String> commend = new ArrayList<String>();
        commend.add(mencoderPath);
        commend.add(upFilePath);
        commend.add("-oac");
        commend.add("mp3lame");
        commend.add("-lameopts");
        commend.add("preset=64");
        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(codcAviPath);
        try {
            // 预处理进程
            ProcessBuilder builder = new ProcessBuilder();
            builder.command(commend);
            builder.redirectErrorStream(true);

            // 进程信息输出到控制台
            Process p = builder.start();
            BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
            String line = null;
            while ((line = br.readLine()) != null) {
                System.out.println(line);
            }
            p.waitFor();// 直到上面的命令执行完,才向下执行
            return codcAviPath;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    
}

class PrintStream extends Thread {
    java.io.InputStream __is = null;

    public PrintStream(java.io.InputStream is) {
        __is = is;
    }

    public void run() {
        try {
            while (this != null) {
                int _ch = __is.read();
                if (_ch != -1)
                    System.out.print((char) _ch);
                else
                    break;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

 

 

// 判断文件夹是否存在
     public static void judeDirExists() {
         File file = new File("d:\\test_dir");
         if (file.exists()) {
            //如果存在则不操作
             //if (file.isDirectory()) { //isDirectory判断此对象是否为文件夹
             //    System.out.println("dir exists");
             //} else {
             //    System.out.println("the same name file exists, can not create dir");
             //}
         } else {
            //不存在则创建
             System.out.println("dir not exists, create it ...");
             file.mkdir();
         }
 
     }

 

注:部分代码转载自https://www.cnblogs.com/smart-hwt/p/8256836.html

评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值