SpringBoot项目实现文件上传并返回上传文件的服务器地址
pox.xml:
<!-- web支持 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- 文件上传 -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.3</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
<!-- 阿里巴巴JSON处理器 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.31</version>
</dependency>
<!--Mybatis 依赖 -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.0</version>
</dependency>
<!--Mysql 驱动 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<!--druid数据源 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.9</version>
</dependency>
application.properties
中添加如下:
#配置文件上传的文件大小限制
spring.servlet.multipart.maxFileSize=300Mb
spring.servlet.multipart.maxRequestSize=500Mb
#静态资源路径
web.upload-path=D:/mimi/
spring.mvc.static-path-pattern=/**
spring.resources.static-locations=classpath\:/META-INF/resources/,classpath\:/resources/,classpath\:/static/,classpath\:/public/,file\:${web.upload-path}
3.1 创建controller类,代码如下:
package com.example.fileupload.controller;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.example.fileupload.service.UploadService;
/**
* 文件上传
*/
@RestController
@RequestMapping("/upload")
public class UploadController {
@Autowired
private UploadService uploadService;
/**
* 视频文件上传
* @param request
* @return
* @throws Exception
*/
@RequestMapping(value ="/uploadVideo",method=RequestMethod.POST)
public Map<String, Object> uploadVideo(MultipartFile file,HttpServletRequest request) throws Exception{
return uploadService.uploadVideo(file, request);
}
/**
* 图片文件上传
* @param request
* @return
* @throws Exception
*/
@RequestMapping(value ="/uploadImage",method=RequestMethod.POST)
public Map<String, Object> uploadImage(MultipartFile file,HttpServletRequest request) throws Exception{
return uploadService.uploadImage(file, request);
}
}
3.2 创建 uploadService和 uploadService的实现类 uploadServiceImpl
uploadService:
package com.example.fileupload.service;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.springframework.web.multipart.MultipartFile;
public interface UploadService {
/**
* 视频文件上传
* @param request
* @return
*/
public Map<String, Object> uploadVideo(MultipartFile file,HttpServletRequest request) throws Exception;
/**
* 图片文件上传
* @param request
* @return
*/
public Map<String, Object> uploadImage(MultipartFile file,HttpServletRequest request) throws Exception;
}
uploadServiceImpl
:
package com.example.fileupload.service.impl;
import java.io.File;
import java.util.*;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import com.example.fileupload.service.UploadService;
import com.example.fileupload.utils.FrameGrabberKit;
@Transactional
@Service("UploadService")
public class UploadServiceImpl implements UploadService{
/**
* 视频文件上传
*/
@Override
public Map<String, Object> uploadVideo(MultipartFile file,HttpServletRequest request) throws Exception {
Map<String, Object> resultMap=new HashMap<String, Object>();
String basePath = request.getScheme() + "://" + request.getServerName()
+ ":" + request.getServerPort()+"/mimi/upload/video/";
Long time = new Date().getTime();
String fileName = file.getOriginalFilename();//文件原始名称
String suffixName = fileName.substring(fileName.lastIndexOf("."));//从最后一个.开始截取。截取fileName的后缀名
String newFileName = time+suffixName; //文件新名称
//设置文件存储路径,可以存放在你想要指定的路径里面
String rootPath="D:/mimi/"+File.separator+"upload/video/"; //上传视频存放位置
String filePath = rootPath+newFileName;
File newFile = new File(filePath);
//判断目标文件所在目录是否存在
if(!newFile.getParentFile().exists()){
//如果目标文件所在的目录不存在,则创建父目录
newFile.getParentFile().mkdirs();
}
//将内存中的数据写入磁盘
file.transferTo(newFile);
//视频上传保存url
String videoUrl = basePath + newFileName;
//视频封面图处理
String newImgName = time+".jpg";
String framefile = rootPath + newImgName;
String imgUrlSave = basePath+newImgName;//图片最终位置路径
//视频截取封面图
String imgUrl=FrameGrabberKit.getVedioImg(videoUrl, framefile, imgUrlSave);
resultMap.put("videoUrl", videoUrl);
resultMap.put("imgUrl", imgUrl);
resultMap.put(ErrorCode.STATE, ErrorCode.SUCCESS);
//System.out.println("上传的文件名为:"+fileName+",后缀名为:"+newFileName);
return resultMap;
}
/**
* 图片文件上传
*/
@Override
public Map<String, Object> uploadImage(MultipartFile file, HttpServletRequest request) throws Exception {
Map<String, Object> resultMap=new HashMap<String, Object>();
String basePath = request.getScheme() + "://" + request.getServerName()
+ ":" + request.getServerPort()+"/mimi/upload/images/";
Long time = new Date().getTime();
String fileName = file.getOriginalFilename();//文件原始名称
String suffixName = fileName.substring(fileName.lastIndexOf("."));//从最后一个.开始截取。截取fileName的后缀名
String newFileName = time+suffixName; //文件新名称
//设置文件存储路径,可以存放在你想要指定的路径里面
String rootPath="D:/mimi/"+File.separator+"upload/images/"; //上传图片存放位置
String filePath = rootPath+newFileName;
File newFile = new File(filePath);
//判断目标文件所在目录是否存在
if(!newFile.getParentFile().exists()){
//如果目标文件所在的目录不存在,则创建父目录
newFile.getParentFile().mkdirs();
}
//将内存中的数据写入磁盘
file.transferTo(newFile);
//图片上传保存url
String imgUrl = basePath + newFileName;
resultMap.put("imgUrl", imgUrl);
resultMap.put(ErrorCode.STATE, ErrorCode.SUCCESS);
return resultMap;
}
}
3.3视频上传获取视频封面图:
1.所需依赖
<!-- 视频获取第一帧 -->
<dependency>
<groupId>org.bytedeco</groupId>
<artifactId>javacv</artifactId>
<version>0.8</version>
</dependency>
2.工具类
package com.example.fileupload.utils;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
import org.bytedeco.javacpp.opencv_core;
import org.bytedeco.javacv.FFmpegFrameGrabber;
import org.bytedeco.javacv.Frame;
/**
* 截取视频图片
* @ClassName: FrameGrabberKit
*/
public class FrameGrabberKit {
/**
* 获取视频图片
* @param videofile 源视频文件路径
* @param framefile 截取帧的图片存放路径
* @param imgfile 视频封面图保存路径
* @return
*/
public static String getVedioImg(String videofile, String framefile,String imgfile){
String ImgUrl="";
//截取封面图
try {
fetchFrame(videofile, framefile);
} catch (Exception e) {
e.printStackTrace();
}
// 完整的ImgUrl
ImgUrl = imgfile;//视频封面图保存路径
return ImgUrl;
}
/**
* 获取指定视频的帧并保存为图片至指定目录
* @param videofile 源视频文件路径
* @param framefile 截取帧的图片存放路径 例:F:\hfkjrecorder\target\4.jpg
* @throws Exception
*/
public static void fetchFrame(String videofile, String framefile) throws Exception {
//long start = System.currentTimeMillis();
File targetFile = new File(framefile);
FFmpegFrameGrabber ff = new FFmpegFrameGrabber(videofile);
ff.start();
int lenght = ff.getLengthInFrames();
int i = 0;
int interceptionFrames = 30;//截取第几帧
//默认截取第50帧,如果第50帧大于视频总帧数的8成直接取长度lenght * 0.3
if(interceptionFrames >= lenght * 0.8) {
interceptionFrames = (int)(lenght * 0.3);
}
Frame f = null;
while (i < lenght) {
// 过滤 前 interceptionFrames 帧,避免出现全黑的图片,依自己情况而定
f = ff.grabFrame();
if ((i > interceptionFrames) && (f.image != null)) {
break;
}
i++;
}
opencv_core.IplImage img = f.image;
int owidth = img.width();
int oheight = img.height();
// 对截取的帧进行等比例缩放 宽350、高160
// if(owidth > oheight) {//宽大于高
//
// }else {//高大于宽
//
// }
int width = 800;
int height = (int) (((double) width / owidth) * oheight);
/**
width - 所创建图像的宽度
height - 所创建图像的高度
imageType - 所创建图像的类型
TYPE_3BYTE_BGR - 表示一个具有 8 位 RGB 颜色分量的图像,对应于 Windows 风格的 BGR 颜色模型,具有用 3 字节存储的 Blue、Green 和 Red 三种颜色。
*/
BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR);
//此方法返回 Graphics2D,但此处是出于向后兼容性的考虑。
bi.getGraphics().drawImage(f.image.getBufferedImage().getScaledInstance(width, height, Image.SCALE_SMOOTH),
0, 0, null);
ImageIO.write(bi, "jpg", targetFile);
//ff.flush();
ff.stop();
// System.out.println(System.currentTimeMillis() - start);
}
}
添加自定义拦截器 继承 WebMvcConfigurationSupport类,重写addResourceHandlers
方法
package com.example.fileupload.config.interceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
/**
* 添加自定义的拦截器(注册拦截器)
* 方法一:extends WebMvcConfigurationSupport(拦截器的配置类,主要配置拦截器的相关参数,
* 并继承以下方法:
* addInterceptors:添加拦截器实例
* addResourceHandlers:静态文件访问配置
* configureViewResolvers:视图配置
* )
* 方法二:implements WebMvcConfigurer
* 方法三:extends WebMvcConfigurerAdapter (WebMvcConfigurer 的实现类)
*
* 在该类标注@Configuration,表明它是一个配置类
*
* 一个项目中只能有一个继承WebMvcConfigurationSupport的@Configuration类(使用@EnableMvc效果相同),
* 如果存在多个这样的类,只有一个配置可以生效。推荐使用implements WebMvcConfigurer 的方法自定义mvc配置。
*
* WebMvcConfigurationSupport的作用:
* 1.可以配置多个路由,放到一个配置类中
* 2.添加自定义拦截器
* @author Administrator
*
*/
@Configuration
public class WebMvcConfig extends WebMvcConfigurationSupport{
/**
* 添加静态资源映射路径,css、js等都放在classpath下的static中
*/
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
/**
* addResourceHandler 指的是对外暴露的访问路径
* addResourceLocations 指的是文件配置的目录
*/
//文件上传路径映射
registry.addResourceHandler("/mimi/upload/**")
.addResourceLocations("file:D:/mimi/upload/");
super.addResourceHandlers(registry);
}
}
需要源码的点击此处下载