配置文件:
//服务器路径
#file.uploadFolder=/root/uploadFiles/
//本地路径
file.uploadFolder=d://uploadFiles/
//上传文件大小和总量限制
spring.servlet.multipart.max-file-size=50Mb
spring.servlet.multipart.max-request-size=50Mb
Controller:
/**
*<p><b>上传Controller类</b></p>
*<p> 上传文件的Controller</p>
* @Author MengMeng
* @Date 2018/10/25 </p>
* @version: 0.1
* @since JDK 1.80_144
*/
@Controller
@RequestMapping("/file")
public class FileController {
@Autowired
private HttpServletRequest request;
@Autowired
private FileService fileService;
@Value("${file.uploadFolder}")
private String uploadFolder;
//处理文件上传
@RequestMapping(value="/upload/{id}", method = RequestMethod.POST)
@ResponseBody
public Map<String,Object> uploadImg(@RequestParam("file") MultipartFile file,HttpServletRequest request,@PathVariable String id) {
Map<String, Object> resultMap = new LinkedHashMap<String, Object>();
String contentType = file.getContentType();
// 获取文件名
String oldName = file.getOriginalFilename();
//System.out.println(oldName);
// 获取文件的后缀,比如图片的jpeg,png
String suffixName = oldName.substring(oldName.lastIndexOf("."));
//System.out.println("上传文件的后缀名为:" + suffixName);
// 文件上传后的路径
SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd-HHmmss");
String time = df.format(new Date());
String[] Name = oldName.split("\\.");
String fileName = time + "-" + Name[0] + suffixName;
//System.out.println(fileName);
//路径
String filePath = uploadFolder;
//自定义实体类:FileSource
FileSource filesource = new FileSource();
filesource.setFilename(fileName);
fileService.save(filesource,filePath,fileName);
//自定义实体类:FileSource
try {
FileUtil.uploadFile(file.getBytes(), filePath, fileName);
//System.out.println("上传成功!");
resultMap.put("status", 200);
resultMap.put("message", "上传成功!");
} catch (Exception e) {
// TODO: handle exception
resultMap.put("status", 500);
resultMap.put("message", "上传异常!");
}
//返回json
return resultMap;
}
}
FileServiceImpl:
@Service
public class FileServiceImpl implements FileService {
@Autowired
private FileRepository fileRepository;
/**
* <b>保存多媒体 </b>
* <p>保存多媒体</p>
* @author MengMeng
* @param filesource 多媒体类
* @param filesource 路径
* @param fileName 名称
* @Date Created date: 2018/10/25
* @return void
*/
@Override
public void save(FileSource filesource, String filePath, String fileName) {
// TODO Auto-generated method stub
String path = filePath + fileName;
filesource.setPath(path);
filesource.setId(UUIDUtils.getUUID32());
filesource.setStatus(1);
filesource.setUpdatetime(new Date());
fileRepository.save(filesource);
}
}
FileUtil:
/**
* 通过该类即可在普通工具类里获取spring管理的bean
* @author MengMeng
* Created date: 2018/10/10
* @version: 0.1
* @since JDK 1.80_144
*/
public class FileUtil {
public static void uploadFile(byte[] file, String filePath, String fileName) throws Exception {
File targetFile = new File(filePath);
if(!targetFile.exists()){
targetFile.mkdirs();
}
FileOutputStream out = new FileOutputStream(filePath+fileName);
out.write(file);
out.flush();
out.close();
}
}