springMVC前后端全套的视频上传源码(入门就能看懂)

前端上传样式:

<!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">
<head>
	<#--  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />  -->
	<meta http-equiv="Content-Type" content="multipart/form-data; charset=utf-8" />
	<title>添加视频表</title>
	<#include "/common/global_css.ftl">
	<link href="${request.getContextPath()}/css/validform/style.css" rel="stylesheet" type="text/css" media="all"/>
	<link href="${request.getContextPath()}/css/chosen/chosen.css" rel="stylesheet" type="text/css"/>
	<style type="text/css">
		body{margin:0px;font-size:12px;color:#999;}
		.form{overflow:auto;background:#F7F7F7;height:205px;}
	</style>
</head>
<body>
	<div class="form">
		<form class="addForm" target="_parent" id="videoAddForm" action="${request.getContextPath()}/course/video/saveVideo" method="post" enctype="multipart/form-data">
			<input type="hidden" id="pageContext" value="${request.getContextPath()}" />
			<input type="hidden" name="partnerId" value="${Session.partnerId}"/>
			<table border="0" cellspacing="0" cellpadding="0" width="100%" style="margin-top:20px;" class="boxTable boxmar">
					<tr>
		            	<td align="right" style="width:150px"><span class="check">*</span>视频名称:</td>
		      			<td style="width:150px">
		      				<input name="videoName" id="videoName" class="cword" datatype="s2-16" nullmsg="请输入视频名称!" errormsg="视频名称至少2个字符,最多16个字符!"/>
		            	</td>
		            	<td>
	    					<div class="Validform_checktip"></div>
	    				</td>
		            </tr>
		            <tr>
		            	<td align="right" style="width:150px"><span class="check">*</span>视频路径保利威vid:</td>
		      			<td style="width:150px">
		      				<input name="videoPath" id="videoPath" class="cword" readonly="readonly" datatype="*" nullmsg="请上传视频!"/>
		            	</td>
		            	<td>
	    					(无需输入)<div class="Validform_checktip"></div>
	    				</td>
		            </tr>
		            <tr>
		            	<td align="right" style="width:80px"><span class="check">*</span>视频上传:</td>
		      			<td colspan="2" style="width:150px">
							<input type="file" id="mp4" style="width:188px;"/>
		      				<input type="button" class="btn" value="上传" onclick="uploadFiles()">
		            	</td>
		            </tr>
	            <tr align="center">
    				<td colspan="3">
    					<input class="btn" type="button" id="saveBtn" value="保存">
    					<input type="button" class="btn dis cancel" id="cancelBtn" value="取消">
    				</td>
  				</tr>
	  		</table>
		</form>
	</div>
	<script type="text/javascript" src="${request.getContextPath()}/js/jquery-1.7.2.min.js"></script>
	<script type="text/javascript" src="${request.getContextPath()}/js/utils/jbox/jquery.jBox.src.js"></script>
	<script type="text/javascript" src="${request.getContextPath()}/js/utils/jbox/jquery.jBox-zh-CN.js"></script>
	<script type="text/javascript" src="${request.getContextPath()}/js/allPage.js" contextPath="${request.getContextPath()}"  id="allPageJs"></script>
	<script type="text/javascript" src="${request.getContextPath()}/js/utils/validform/Validform_v5.3.2.js"></script>
	<script type="text/javascript" src="${request.getContextPath()}/js/utils/chosen/chosen.jquery.min.js"></script>
	<script type="text/javascript" src="${request.getContextPath()}/js/my97date/WdatePicker.js"></script>
	<script type="text/javascript">
		$(function(){
			$('#videoAddForm').Validform({
				btnSubmit:"#saveBtn", 
				tiptype:2,
				showAllError:true
			});
			$('.chosen').chosen({
				"no_results_text":'未找到匹配数据!',
				"width":"120px",
				"allow_single_deselect":true
			});
			$('#cancelBtn').click(function(){
				parent.jBox.close(true);
			});
		});
		//上传视频到本地服务器
		function uploadFiles(){
		 	 var videoName=$("#videoName").val();
		 	 var title="";
		 	 if(videoName==""||videoName==null){
		 	 	title=$('#mp4')[0].files[0].name.substring(0,$('#mp4')[0].files[0].name.indexOf("."));
		 	 }else{
		 	 	title=videoName;
		 	 }
		 	 $("#JSONRPC").val("{'title':'"+title+"','tag':'无','desc':'视频文件'}");
		 	 console.log($("#JSONRPC").val());
			var myFormData = new FormData();
			myFormData.append('mp4',$('#mp4')[0].files[0]);
			console.log($('#mp4')[0].files[0]);
			var index= $('#mp4')[0].files[0].name.lastIndexOf(".");
			//获取后缀
			var ext = $('#mp4')[0].files[0].name.substr(index+1);
		     	$.ajax({
		           type:"post",
		           url:"${request.getContextPath()}/uploadfile/uploadMp4",
		           data:myFormData,
		           cache: false,
		           async:false,
		           processData: false,
		           contentType: false,
		           success:function(data) {
					    parent.jBox.tip('上传已完成。', 'success');
		           		console.log(data);
			       },error:function(data) {
			       		console.log(data);
			       }
			  });
	}	
	</script>
</body>
</html>

后端代码:

package com.nuocai.modules.uploadfile.controller;

import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
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.nuocai.core.common.utils.upload.FileUploadConstants;
import com.nuocai.core.mybase.Constants;

@Controller
@RequestMapping("/uploadfile")
public class UploadController {
	//获取到真是路径
	private static String getSavePath(String proVal) {

		if (proVal != null && proVal.equals("")) {
			proVal = "";
		}
		String saveFilePath = FileUploadConstants.getPropValue(proVal);
		if (saveFilePath == null || saveFilePath.equals("")) {
			return null;
		}
		if (!saveFilePath.endsWith("/"))
			saveFilePath += "/";
		// 生成文件保存路径
		File aSaveFile = new File(saveFilePath);
		if (!aSaveFile.isDirectory())
			aSaveFile.mkdirs();
		return saveFilePath;
	}
	/**
	 * UUID命名
	 * 
	 */
	public static String reFileNameByUUID(String filePath, String fileName) {
		String uFileName = UUID.randomUUID().toString();
		uFileName = uFileName.substring(0, 8) + uFileName.substring(9, 13) + uFileName.substring(14, 18) + uFileName.substring(19, 23) + uFileName.substring(24);
		int p = fileName.lastIndexOf(".");
		fileName = uFileName + fileName.substring(p, fileName.length());
		File file = new File(filePath + fileName);
		if (file.exists()) {
			fileName = reFileNameByUUID(filePath, fileName);
		}
		return fileName;
	}
	//**********************uploadMp4***************
	@SuppressWarnings("unused")
	@ResponseBody
	@RequestMapping(value = { "/uploadMp4" }, method = RequestMethod.POST)
	public String uploadMp4(HttpServletRequest request, @RequestParam(value = "mp4", required = false) MultipartFile file) throws Exception {
		String savePath = getSavePath("FILE_PATH_Mp4");
		String path = savePath;// 文件路径
		if (file != null) {// 判断上传的文件是否为空
			String type = null;// 文件类型
			String fileName = file.getOriginalFilename();// 文件原名称
			fileName = reFileNameByUUID(savePath, fileName);
			// 判断文件类型
			type = fileName.indexOf(".") != -1 ? fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length()) : null;
			if (type != null) {// 判断文件类型是否为空
				if ("mp4".equals(type)) {
					// 项目在容器中实际发布运行的根路径
					String realPath = request.getSession().getServletContext().getRealPath("/");
					// 自定义的文件名称
					String trueFileName = String.valueOf(System.currentTimeMillis()) + "." + type;
					// 设置存放图片文件的路径
					path = savePath + fileName;
					System.out.println("存放视频文件的路径:" + savePath);
					// 转存文件到指定的路径
					file.transferTo(new File(path));
					return Constants.SAVE_FILE_MP4 + fileName;
				}
			} else {
				return "false";
			}
		} else {
			return "false";
		}
		return "false";	
	}
}

后端所需要的工具类:

package com.nuocai.core.common.utils.upload;
import java.io.InputStream;
import java.util.Properties;

public class FileUploadConstants {
	public static String EXCELPATH_USER = "";
	
	private static Properties prop=null;
	
	static{
		String path="/config/fileUploadSavePath_windows.properties";
		if(isLinux()){
			path="/config/fileUploadSavePath_linux.properties";
		}
		InputStream in=FileUploadConstants.class.getResourceAsStream(path);
		if(in!=null){
			prop=new Properties();
			try {
				prop.load(in);
				EXCELPATH_USER=prop.getProperty("EXCELPATH_USER");
			} catch (Exception e) {
				throw new RuntimeException(e);
			}
		}
	}
	
	public static String getPropValue(String key){
		String path="/config/fileupload/fileUploadSavePath_windows.properties";
		String val = null;
		if(isLinux()){
			path="/config/fileupload/fileUploadSavePath_linux.properties";
		}
		InputStream in=FileUploadConstants.class.getResourceAsStream(path);
		if(in!=null){
			prop=new Properties();
			try {
				prop.load(in);
				val = prop.getProperty(key);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return val;
	}
	
	public  static boolean isLinux(){
		String osType = System.getProperties().getProperty("os.name").toLowerCase();
		if(osType.startsWith("windows")){
			return false;
		}
		else{
			return true;
		}
	}
}




package com.nuocai.core.mybase;

import com.nuocai.core.common.utils.upload.FileUploadConstants;
import com.nuocai.core.myutil.PropertiesLoader;


/**
 * 全局常量
 * 
 * @author zj
 * 
 */
public abstract class Constants {

	/**
     * 文件存储路径
     */
    public static final String SAVE_FILE_JS="http://static.gswldx.com/js/";
    public static final String SAVE_FILE_CSS="http://static.gswldx.com/css/";
    public static final String SAVE_FILE_IMAGE="http://static.gswldx.com/image/";
    public static final String SAVE_FILE_MP4="http://static.gswldx.com/Mp4/";
    public static final String SAVE_FILE_EXCEL="http://static.gswldx.com/upload/excel/";
    public static final String SAVE_FILE_FILES="http://static.gswldx.com/file/";
}

最好就是Nginx动静分离配置:

server {
	listen       80;
	server_name  static.gswldx.com;
	access_log  static.yijian119.com.access.log;
	location / {		
		#location ~ .*\.(gif|jpg|jpeg|png|bmp|swf|js|css)$ {
        	#        valid_referers *.wafutech.com;
                #	if ($invalid_referer) {
                #        	return 403;
                #	}
        	#}

		root   C:/web/project/js_css_static/;
		#index  index.html index.htm;
	}

}

最后需要注意的时,当文件视频过于大的时候,此时就需要去配置文件里面修改MultipartFile的文件限制大小,完毕,小白直接粘贴也可以看懂,加油!

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值