文件上传:简单的demo

/*
接收前台传来的视频,把视频放到服务器中,并把视频地址保存到数据库
*/
@RequestMapping(value = "/vms/media_main/saveVideo.do")
public void saveVideo(@RequestParam("file")CommonsMultipartFile file, HttpServletRequest req, HttpServletResponse res) {

Videoinfo videoinfo = new Videoinfo();
String date = DateUtil.dateToString("yyyyMMdd",new Date());
String path = "/home/nginx/vod/videos/upload/"+date+"/"+username;
String name = file.getOriginalFilename(); //上传时的文件名
int k = name.lastIndexOf(".");
String videoname = name.substring(0,k);
String format = name.substring(k+1).toUpperCase();//获取文件类型
Date date1 = new Date();
SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//创建一个图片名字
String fileName = new Date().getTime()+(int)(Math.random()*100)+name.substring(name.lastIndexOf("."));
InputStream is;
OutputStream os;
String video = "" ;
try {
is = file.getInputStream();
File paths = new File(path);
if (!paths.exists()) {
paths.mkdirs();
}
os = new FileOutputStream(new File(path,fileName));
int len = 0;
byte[] buffer = new byte[400];
while((len=is.read(buffer))!=-1){
os.write(buffer,0,len);
}
os.close();
is.close();

video = "videos/upload/"+date+"/"+username+"/"+fileName;

videoinfo.setPath(video);
videoinfo.setFormat(format);
videoinfo.setVideoname(videoname);
videoinfo.setCreatetime(format1.format(date1));
videoinfo.setStatus(1);
videoService.addSave(videoinfo);

} catch (Exception e) {
e.printStackTrace();
}
}
<form action="" enctype="multipart/form-data" method="post">
 上传文件:<input type="file" name="file"><br/> 
<input type="submit" value="提交"> 
</form>

 

posted @ 2017-03-03 08:45  -J  阅读(1653)  评论(1编辑  收藏  举报