ssm项目实现文件上传方法一:
1,在springmvc.xml中添加:
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"
p:defaultEncoding="UTF-8"></bean>
2,在controller中:通过注解@RequestParam("file") MultipartFile file就可以获取到客户端传递的文件。对file操作执行上传文件操作
@RequestMapping("/video_submit")
@ResponseBody
public apiResult<Test_Result> videoSubmit(@RequestParam("file") MultipartFile file, @RequestParam("id") int id, @RequestParam("train_id") int train_id,HttpServletRequest request, HttpServletResponse response) throws IOException{
String msg="";
System.out.println("上传视频");
apiResult<Test_Result> apiresult = new apiResult<Test_Result>();
Test_Result result = new Test_Result();
String fileName = file.getOriginalFilename();//得到原来的文件名在客户机的文件系统名称
System.out.println("fileName= "+fileName);
try {
//获取文件字节数组
byte [] bytes = file.getBytes();//将文件内容转化成一个byte[] 返回
//通过读取配置文件,获得文件上传的目标地址
Properties properties = new Properties();
InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("resource/fileAddress.properties");
properties.load(inputStream);
String path_store = properties.getProperty("address");
String targetfolder = properties.getProperty("targetfolder");//需要转码视频的地址
//文件存储路径(/fileupload1/ 这样会在根目录下创建问价夹)
// File pfile = new File(request.getSession().getServletContext().getRealPath(path_store));是获取的的tamcat的绝对路径,部署项目后相当于项目的路径。tomcat路径下的fileupload1
File pfile = new File(path_store);//将上传的文件存放在磁盘固定位置
//判断文件夹是否存在
if(!pfile.exists()){
//不存在时,创建文件夹
pfile.mkdirs();
}
System.out.println(request.getSession().getServletContext().getRealPath("/fileupload1/"));
//创建文件
File copyfile = new File(pfile, fileName);
//写入指定文件夹
OutputStream out = new FileOutputStream(copyfile);
out.write(bytes);// file.transferTo(targetFile);
out.close();
//视频是否需要转码
// 获取文件后缀名
String filename_extension = fileName.substring(fileName
.lastIndexOf(".") + 1);
if (filename_extension.equals("avi") || filename_extension.equals("rm")
|| filename_extension.equals("rmvb") || filename_extension.equals("wmv")
|| filename_extension.equals("3gp") || filename_extension.equals("mov")
||filename_extension.equals("flv") || filename_extension.equals("ogg")
) {//需要转码的文件
ConverVideoUtils c = new ConverVideoUtils(path_store+fileName);
String targetExtension = ".mp4"; //设置转换的格式
boolean isDelSourseFile = true;
//删除源文件
String beginConver = c.beginConver(targetExtension,isDelSourseFile);
System.out.println("=================转码过程彻底结束=====================");
result.setVideo(beginConver.substring(beginConver
.indexOf("/") ));
}else{
result.setVideo((path_store+fileName).substring(path_store
.indexOf("/") ));//在数据库表中存视频地址是相对路径(不需要转码的文件直接存放在D:/tomcat/upload)
}
//
//将上传的视频地址存入数据库:
result.setId(id);
result.setTrain_id(train_id);
int i = sReportService.videoSubmit(result);
if(i!=0){
//视频保存成功
apiresult.setCode(0);
}else{
apiresult.setMsg("上传视频失败");
}
} catch (IOException e) {
e.printStackTrace();
}
return apiresult;
}
ssm项目实现文件上传方法二:
服务器端通过fileupload工具获取到请求参数,再对参数分析,得到文件参数:
@RequestMapping("/video_submit")
@ResponseBody
public apiResult<Test_Result> videoSubmit(HttpServletRequest request, HttpServletResponse response) throws IOException{
apiResult<Test_Result> apiresult = new apiResult<Test_Result>();
try {
//1、创建磁盘文件项工厂
//作用:设置缓存文件的大小 设置临时文件存储的位置
String path_temp = request.getSession().getServletContext().getRealPath("temp");
//DiskFileItemFactory factory = new DiskFileItemFactory(1024*1024, new File(path_temp));
//1、创建磁盘文件项工厂--一些相关的配置的设置 缓存的大小 临时目录的位置
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold(1024*1024);
factory.setRepository(new File(path_temp));
//2,创建文件上传核心类
ServletFileUpload upload = new ServletFileUpload(factory);
//设置上传文件的名称的编码
upload.setHeaderEncoding("UTF-8");
//ServletFileUpload的API
boolean multipartContent = upload.isMultipartContent(request);//判断表单是否是文件上传的表单
if(multipartContent)
{
System.out.println("是文件上传");
//3,解析request获得文件项对象集合
List<FileItem> parseRequest = upload.parseRequest(request);
if(parseRequest==null)
{
System.out.println("传递空");
}
//4,遍历文件项集合
for(FileItem item : parseRequest){
//判断是否是普通文件项
boolean formField = item.isFormField();
if(formField){
//普通文件项获得表单中的数据存入product实体中
String fieldName = item.getFieldName();
String fieldValue = item.getString("utf-8");
System.out.println(fieldName+" "+fieldValue);//fieldName玩家id,fieldValue训练id
}
else{
//文件上传项获得文件名称和文件内容
String file = item.getName();//获得上传文件的名字
InputStream in = item.getInputStream();//以流的方式获得文件的内容,获得输入流
//通过读取配置文件,获得文件上传的目标地址
Properties properties = new Properties();
InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("resource/fileAddress.properties");
properties.load(inputStream);
String path_store = properties.getProperty("address");
//文件存储路径(/fileupload1/ 这样会在根目录下创建问价夹)
// File pfile = new File(request.getSession().getServletContext().getRealPath(path_store));是获取的的tamcat的绝对路径,部署项目后相当于项目的路径。tomcat路径下的fileupload1
File pfile = new File(path_store);//将上传的文件存放在磁盘固定位置
//判断文件夹是否存在
if(!pfile.exists()){
//不存在时,创建文件夹
pfile.mkdirs();
}
//创建文件
File copyfile = new File(pfile, file);
//写入指定文件夹
OutputStream out = new FileOutputStream(copyfile);
byte[] ch = new byte[1024];//定义数组,用于存储读到的字节
int len =0;
while((len=in.read(ch))!=-1){//in.read返回-1说明对到文件的末尾
out.write(ch, 0, len);// 将指定 byte 数组中从偏移量 off 开始的 len 个字节写入此文件输出流。
}
if(in!=null){
in.close();
}
if(out!=null){
out.flush();
out.close();
}
}
}
apiresult.setMsg("测试");
}else{
System.out.println("不是文件上传表单");
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return apiresult;
}
ps:需要注意的如果用方法一,对springmvc.xml文件设置了,再改为方法二的时候,注意要删除springmvc.xml中添加的内容