安卓端採用okhttp網絡框架上傳視頻/圖片到服務器(二)

安卓端採用okhttp網絡框架上傳視頻/圖片到服務器(一)

安卓端上傳至服務器端的代碼與Web端上傳服務器端代碼相比,視頻文件處理、截圖等操作代碼是一致的。

只是前面如何拿到視頻文字信息及視頻文件有些不同。

		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		MultipartFile file = multipartRequest.getFile("file");
		String video_details = multipartRequest.getParameter("details");

需要對拿到的json格式字符串進行解析:

		List<Video> video_list = OneVideoinformationJsonUtils.OneVideoinformationJsonToList(video_details);

服務器端同樣採用SSM框架,用到了註解。

controller層代碼如下:

/***********************************視頻上傳***************************************/
	String uploadVideo1 = Contants.targetfolder;//視頻最終保存的目錄
	String uploadVideoImgPath = Contants.imageRealPath;
	@RequestMapping("/ToUploadVideo")
	public void ToUploadVideo(HttpServletResponse response,HttpServletRequest request) {
		response.setCharacterEncoding("UTF-8");
		System.out.println("ToUploadVideo>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
		
		String NewVideopath = null;
		String filename3 = null;
		String imgname = null;
		String imgpath =null;
		
		Date day = new Date();
		SimpleDateFormat dft = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String video_time_upload = dft.format(day);
		
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		MultipartFile file = multipartRequest.getFile("file");
		String video_details = multipartRequest.getParameter("details");
		
		System.out.println("details........"+video_details);
	
		List<Video> video_list = OneVideoinformationJsonUtils.OneVideoinformationJsonToList(video_details);
		String video_author = video_list.get(0).getVideo_author();
		String video_title = video_list.get(0).getVideo_title();
		String video_category = video_list.get(0).getVideo_category();
		String video_source = video_list.get(0).getVideo_source();
		String video_classes = video_list.get(0).getVideo_classes();
		String video_money = video_list.get(0).getVideo_money();
		String video_introduce = video_list.get(0).getVideo_introduce();
		
		if (file.getSize() != 0) {
	
			//如果上傳文件後綴名爲MP4,則直接上傳至最終文件夾
			String path2 = uploadVideo1;			
			//判斷是否創建文件夾
			File TempFile = new File(path2);
			if (TempFile.exists()) {
				if (TempFile.isDirectory()) {
					System.out.println("該文件夾存在。");
				}else {
					 System.out.println("同名的文件存在,不能創建文件夾。");
				}
			}else {
				 System.out.println("文件夾不存在,創建該文件夾。");
				 TempFile.mkdir();
			}			
			// 獲取上傳時候的文件名
			String filename = file.getOriginalFilename();
			System.out.println("上傳時候的文件名爲:filename="+filename);			
			// 獲取文件後綴名
			String filename_extension = filename.substring(filename
					.lastIndexOf(".") + 1);
			System.out.println("視頻的後綴名:filename_extension="+filename_extension);			
			//文件名添加時間戳,避免相同文件名出現;同時,時間戳用作視頻no
			long filename1 = new Date().getTime();			
			filename = filename.substring(0, filename.lastIndexOf(".")) + "_" + Long.toString(filename1)+"."+filename_extension;
			String video_no = "V"+Long.toString(filename1);
			System.out.println("視頻編號 video_no="+video_no);
			System.out.println("添加了時間戳的文件名:filename="+filename);			
			//去掉後綴的文件名
			String filename2 = filename.substring(0, filename.lastIndexOf("."));
			System.out.println("去掉後綴的文件名:"+filename2);			
			

			//上傳到服務器
			try {
				System.out.println("寫入本地磁盤/服務器");
				InputStream is = file.getInputStream();
				OutputStream os = new FileOutputStream(new File(path2, filename));
				int len = 0;
				byte[] buffer = new byte[2048];
					
				while ((len = is.read(buffer)) != -1) {
					os.write(buffer, 0, len);
				}
				os.close();
				os.flush();
				is.close();
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
				
			System.out.println("========視頻上傳完成=======");
			
			String Mp4path = uploadVideo1;
			filename3 = filename2+".mp4";
			NewVideopath =Mp4path +filename3;
			System.out.println("視頻的url:"+NewVideopath);
				
			ConverVideoUtils cv = new ConverVideoUtils();
			if (cv.processImg(NewVideopath)) {
				System.out.println("截圖成功! ");
				//獲取轉碼後的mp4截圖名
				String imgpath0 = uploadVideoImgPath;
				imgname = filename2+".png";
				imgpath =imgpath0 +imgname;
				System.out.println("視頻的截圖url:"+imgpath);
					
			} else {
				System.out.println("截圖失敗! ");
			}
							
			System.out.println("開始進行數據庫操作。。。。。。。。。");
						
			Video video = new Video();
						
			//數據庫存儲信息
			video.setVideo_no(video_no);
			video.setVideo_author(video_author);
			video.setVideo_title(video_title);
			video.setVideo_category(video_category);
			video.setVideo_classes(video_classes);
			video.setVideo_source(video_source);
			video.setVideo_money(video_money);
			video.setVideo_introduce(video_introduce);
			video.setVideo_time_upload(video_time_upload);
			video.setVideo_filename(filename3);
			video.setVideo_imgname(imgname);
			video.setVideo_path(NewVideopath); 			//已轉碼後的視頻存放地址
			video.setVideo_imgpath(imgpath);
						
			// 實現對數據的更新
			int n = 0;
			n = videoService.saveVideo(video);
			
			try {
				PrintWriter out = response.getWriter();
				if(n != 0) {
					System.out.println("寫入數據庫成功!");
					out.write("true");
				}else {
					System.out.println("寫入數據庫失敗!");
					out.write("false");
				}
				response.flushBuffer();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}
	}

ConverVideoUtils.java文件,給視頻截圖。

package cn.lijx.mytools;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

public class ConverVideoUtils {
	private String filerealname;				 			//文件名不包括後綴名
	private String filename; 								//包括後綴名
	private String imageRealPath = Contants.imageRealPath;   // 截圖的存放目錄
	
	public ConverVideoUtils() {
	}

	//重構構造方法,傳入源視頻
	public ConverVideoUtils(String path) {
		sourceVideoPath = path;
		System.out.println("ConverVideoUtils.jsp文件:sourceVideoPath="+sourceVideoPath);
	}

	//set和get方法傳遞path
	public String getPATH() {
		return sourceVideoPath;
	}

	public void setPATH(String path) {
		sourceVideoPath = path;
	}
	
	/**
	 * 視頻截圖
	 */
	public boolean processImg(String sourceVideoPath) {
		System.out.println("截圖===得到原視頻路徑sourceVideoPath===="+sourceVideoPath);
		
		//先確保保存截圖的文件夾存在
		File TempFile = new File(imageRealPath);//imageRealPath爲截圖存放路徑
		System.out.println("截圖===截圖存放路徑imageRealPath===="+imageRealPath);
		
		if (TempFile.exists()) {
			if (TempFile.isDirectory()) {
				System.out.println("該文件夾存在。");
			}else {
				 System.out.println("同名的文件存在,不能創建文件夾。");
			}
		}else {
			 System.out.println("文件夾不存在,創建該文件夾。");
			 TempFile.mkdir();
		}
		
		File fi = new File(sourceVideoPath);
		filename = fi.getName();//獲取視頻文件的名稱。
		filerealname = filename.substring(0, filename.lastIndexOf(".")); //獲取視頻名+不加後綴名 後面加.toLowerCase()轉爲小寫		
		List<String> commend = new ArrayList<String>();
		//第一幀: 00:00:01 
		//截圖命令:time ffmpeg -ss 00:00:02 -i test1.flv -f image2 -y test1.jpg	
		commend.add(ffmpegpath);			//指定ffmpeg工具的路徑
		commend.add("-ss");
		commend.add("00:00:02");			//2是代表第2秒的時候截圖
		commend.add("-i");
		commend.add(sourceVideoPath);		//截圖的視頻路徑
		commend.add("-f");
		commend.add("image2");
		commend.add("-y");
		commend.add(imageRealPath + filerealname + ".png");		//生成截圖xxx.png
		System.out.println("截圖===給commend添加值後,檢驗imageRealPath===="+imageRealPath);
		System.out.println("截圖===給commend添加值後,檢驗filerealname===="+filerealname);
		
		 //打印截圖命令
        StringBuffer test = new StringBuffer();    
        System.out.println("截圖===commend.size=="+commend.size());
        for (int i = 0; i < commend.size(); i++) {    
            test.append(commend.get(i) + " ");  
            System.out.println("截圖===commend");
        }    
        System.out.println("截圖命令爲:"+test);    
		
        //轉碼後完成截圖功能-還是得用線程來解決
		try {
				 //調用線程處理命令
				ProcessBuilder builder = new ProcessBuilder();
				builder.command(commend);
				Process p = builder.start(); 
				
				//獲取進程的標準輸入流  
				final InputStream is1 = p.getInputStream();   
				//獲取進程的錯誤流  
	            final InputStream is2 = p.getErrorStream(); 
	          //啓動兩個線程,一個線程負責讀標準輸出流,另一個負責讀標準錯誤流  
	            new Thread() {    
	                public void run() {    
	                    BufferedReader br = new BufferedReader(    
	                            new InputStreamReader(is1));    
	                    try {    
	                        String lineB = null;    
	                        while ((lineB = br.readLine()) != null) {    
	                            if (lineB != null){    
	                                System.out.println("截圖===lineB========="+lineB);    //必須取走線程信息避免堵塞
	                            }
	                        }    
	                    } catch (IOException e) {    
	                        e.printStackTrace();    
	                    } 
	                    //關閉流
	                    finally{  
	                        try {  
	                          is1.close();  
	                        } catch (IOException e) {  
	                           e.printStackTrace();  
	                       }  
	                     }  
	                    
	                }    
	            }.start();    
	            new Thread() {    
	                public void run() {    
	                    BufferedReader br2 = new BufferedReader(    
	                            new InputStreamReader(is2));    
	                    try {    
	                        String lineC = null;    
	                        while ((lineC = br2.readLine()) != null) {    
	                            if (lineC != null)   { 
	                                System.out.println("截圖===lineC========="+lineC);   //必須取走線程信息避免堵塞
	                            }
	                        }    
	                    } catch (IOException e) {
	                        e.printStackTrace();  
	                    }  
	                    
	                    //關閉流
	                    finally{  
	                        try {  
	                            is2.close();  
	                        } catch (IOException e) {  
	                            e.printStackTrace();  
	                        }  
	                      } 
	                    
	                }    
	            }.start();   
	            p.waitFor();
            System.out.println("截圖進程結束");
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}

}

OneVideoinformationJsonUtils.java文件,用於json解析。

package cn.lijx.mytools;

import java.util.ArrayList;
import java.util.List;

import cn.lijx.domain.Video;
import net.sf.json.JSONException;
import net.sf.json.JSONObject;

public class OneVideoinformationJsonUtils {
    public static List<Video> OneVideoinformationJsonToList(String jsonString){
        List<Video> list = new ArrayList<>();
        System.out.println("OneVideoinformationJsonUtils,得到的jsonString爲>>>>>>"+jsonString);

        try {
            JSONObject obj = new JSONObject(jsonString.substring(jsonString.indexOf("{"), jsonString.lastIndexOf("}")+1));
            System.out.println("封裝完成");

            //將jsonObject中的value值封裝成屬性值
            Video info=new Video();
            info.setVideo_author(obj.getString("video_author"));
            info.setVideo_title(obj.getString("video_title"));
            info.setVideo_category(obj.getString("video_category"));
            info.setVideo_source(obj.getString("video_source"));
            info.setVideo_classes(obj.getString("video_classes"));
            info.setVideo_introduce(obj.getString("video_introduce"));
            info.setVideo_money(obj.getString("video_money"));

            System.out.println("將value值封裝成屬性值完成");
            list.add(info);
            System.out.println("OneVideoinformationJsonUtils>>>>>>"+list);

        } catch (JSONException e) {
            e.printStackTrace();
        }
        return list;
    }
}

 Contants.java文件,用於設置文件存儲路徑。

package cn.lijx.mytools;

public class Contants {
	public static final String videoRealPath = "D:/apache-tomcat-9.0.31/webapps/SDD/websiteimages/temp/"; 	// 需要被截圖的視頻目錄
	public static final String targetfolder = "D:/apache-tomcat-9.0.31/webapps/SDD/websiteimages/finshvideo/"; // 轉碼後視頻保存的目錄
	public static final String imageRealPath = "D:/apache-tomcat-9.0.31/webapps/SDD/websiteimages/finshimg/"; // 截圖的存放目錄
}

服務器端代碼寫好啦!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章