#应用场景#
- 该后端开发接口适用 图片/视频上传,返回路径名称场景
1.视频上传
写在Controller层
这里只是一个接收,调用uploadObject方法上传oss
public OmsResult<FileUploadDto> goodsUploadVideo(@RequestParam(value = "file") MultipartFile multipartFile, HttpServletRequest request, HttpServletResponse response) {
FileUploadDto fileUploadDto = new FileUploadDto();
if (null == multipartFile) {
return OmsResult.error("文件传输格式错误");
}
String originalFilename = multipartFile.getOriginalFilename();
if (StringUtil.isEmpty(originalFilename)) {
return OmsResult.error("文件名缺失");
}
if (originalFilename != null) {
// 校验文件扩展名
if (!checkFormatVideo(originalFilename)) {
return OmsResult.error("仅支持mp4, mov, m4v, flv, x-flv, mkv, wmv, avi格式");
}
// 校验文件大小
if (multipartFile.getSize() > FileSizeConstant.FILE_20MB) {
return OmsResult.error("文件大小不得超过20MB");
}
try {
String[] split = originalFilename.split("\\.");
// 拼接上传文件名GV+当前时间(24小时)+随机数
String fileName = "GV" + "当前时间" + randomLetterGenerator() + "." + split[1];
// 获取文件输入流
InputStream inputStream = multipartFile.getInputStream();
//上传文件到OSS
//这行代码调用ossClient对象的uploadObject2OSS4SimplePathByIn方法,将文件上传到OSS。其中,inputStream是文件输入流,fileName是文件名,GV是文件在OSS中的存储路径前缀
String url = ossClient.uploadObject(inputStream, fileName, "GV");
log.info("goodsUploadVideo URL:{}", url);
fileUploadDto.setFileUrl(fileName);
fileUploadDto.setVideoSize(String.valueOf(multipartFile.getSize()));
return OmsResult.success(fileUploadDto);
} catch (Exception e) {
log.error("goodsUploadVideo Error", e);
return OmsResult.error("上传文件失败");
}
/**
* 随机生成4位大写英文字母
* @return
*/
private String randomLetterGenerator() {
SecureRandom random = new SecureRandom();
StringBuilder randomLetters = new StringBuilder();
for (int i = 0; i < 4; i++) {
int index = random.nextInt(26);
char letter = (char) ('a' + index);
randomLetters.append(letter);
}
return randomLetters.toString();
}
后缀校验
private boolean checkFormatVideo(String originalFilename) {
if (StringUtil.isEmpty(originalFilename)) {
return false;
}
String s = originalFilename.toLowerCase();
//需要什么自己加后缀
return s.endsWith(".mp4") || s.endsWith(".mov") || s.endsWith(".m4v") || s.endsWith(".flv")
|| s.endsWith(".x-flv") || s.endsWith(".mkv") || s.endsWith(".wmv") || s.endsWith(".avi");
}
⭐最后说下uploadObject这个方法
这部分一般公司都有公共的轮子
public String uploadObject(InputStream in, String fileName, String folder, String... bucketName) {
if (StringUtils.isEmpty(folder)) {
folder = "";
}
String bucketNameTmp = this.bucketName;
if (bucketName != null && bucketName.length > 0) {
bucketNameTmp = bucketName[0];
}
String url = null;
try {
ObjectMetadata metadata = new ObjectMetadata();
metadata.setContentLength((long)in.available());
metadata.setCacheControl("no-cache");
metadata.setHeader("Pragma", "no-cache");
metadata.setContentEncoding("utf-8");
metadata.setContentType(this.getContentType(fileName));
metadata.setContentDisposition("filename/filesize=" + fileName);
PutObjectResult putResult = this.ossClientConfig.putObject(bucketNameTmp, folder + fileName, in, metadata);
String resultStr = putResult.getETag();
if (StringUtils.isNotEmpty(resultStr)) {
url = folder + fileName;
}
} catch (Exception var10) {
var10.printStackTrace();
log.error("上传阿里云OSS服务器异常." + var10.getMessage(), var10);
}
return url;
}
这个是用于将文件上传到阿里云对象存储服务(OSS)的Java方法
- 使用
ossClientConfig
对象的putObject
方法执行上传操作。这个方法需要存储桶名称、文件路径(文件夹+文件名)、输入流和元数据信息。- 从
PutObjectResult
对象中获取ETag(一个代表文件内容的哈希值),并检查它是否为空。如果不为空,则设置url
为上传文件的路径(文件夹+文件名)。- 如果在上传过程中发生异常,则捕获该异常并打印堆栈跟踪,并记录错误日志。
前端vue逻辑和oss方法可以参考一下这篇文章
http://t.csdnimg.cn/2yaig
2.图片上传
controller逻辑
public void uploadImportFile(@RequestParam("fileImport") MultipartFile fileImport, HttpServletRequest request, HttpServletResponse response) {
JSONObject result = new JSONObject();
BufferedInputStream in = null;
try {
// 上传文件类型 1商贸店铺申请附件 2商贸店铺LOGO附件 3其他
String fileType = request.getParameter("fileType");
if (null == fileImport || StringUtils.isBlank(fileImport.getOriginalFilename())) {
result.put(ResponseConstant.RESPONSE_CODE, "400");
result.put(ResponseConstant.RESPONSE_MSG, "上传的文件为空,请重新上传");
this.writeData(result, response);
return;
}
String fileName = fileImport.getOriginalFilename();
// 判断文件大小
if ("1".equals(fileType) || "2".equals(fileType)) {
if("1".equals(fileType)){
if (fileImport.getSize() > FileSizeConstant.FILE_1MB) {
result.put(ResponseConstant.RESPONSE_CODE, "400");
result.put(ResponseConstant.RESPONSE_MSG, "当前上传的文件过大,大小不能超出1M");
this.writeData(result, response);
return;
}
} else if ("2".equals(fileType) && fileImport.getSize() > FileSizeConstant.FILE_20MB) {
result.put(ResponseConstant.RESPONSE_CODE, "400");
result.put(ResponseConstant.RESPONSE_MSG, "当前上传的文件过大,大小不能超出20M");
if (!fileName.endsWith(".png") && !fileName.endsWith(".jpeg") && !fileName.endsWith(".jpg")) {
result.put(ResponseConstant.RESPONSE_CODE, "400");
result.put(ResponseConstant.RESPONSE_MSG, "上传的文件类型错误,请重新上传,只支持png、jpeg、jpg格式文件");
this.writeData(result, response);
return;
}
} else {
if (fileImport.getSize() > FileSizeConstant.FILE_32MB) {
result.put(ResponseConstant.RESPONSE_CODE, "400");
result.put(ResponseConstant.RESPONSE_MSG, "当前上传的文件过大,大小不能超出32M");
this.writeData(result, response);
return;
}
if (!fileName.endsWith(".xls") && !fileName.endsWith(".xlsx")
&& !fileName.endsWith(".pdf") && !fileName.endsWith(".png") && !fileName.endsWith(".jpeg") && !fileName.endsWith(".jpg")
&& !fileName.endsWith(".rar") && !fileName.endsWith(".zip")) {
result.put(ResponseConstant.RESPONSE_CODE, "400");
result.put(ResponseConstant.RESPONSE_MSG, "上传的文件类型错误,请重新上传,pdf、png、jpeg、jpg、xls、xlsx、rar、zip");
this.writeData(result, response);
return;
}
}
//上传文件的时间
String uploadTime = DateUtils.getToday("yyyyMMddHHmmssSSS") + SaltUtil.getRandom();
String fileNameNew = uploadTime + SaltUtil.randomGenerate() + fileName.substring(fileName.lastIndexOf("."));
in = new BufferedInputStream(fileImport.getInputStream());
String url = ossClient.uploadObject(in, fileNameNew, null);
if (StringUtils.isNotBlank(url)) {
result.put(ResponseConstant.RESPONSE_CODE, "200");
result.put(ResponseConstant.RESPONSE_MSG, "上传成功");
result.put("data", url);
this.writeData(result, response);
} else {
result.put(ResponseConstant.RESPONSE_CODE, "400");
result.put(ResponseConstant.RESPONSE_MSG, "上传失败,请重新上传");
this.writeData(result, response);
}
} catch (Exception e) {
log.error("上传文件异常:{}", e);
result.put(ResponseConstant.RESPONSE_CODE, "500");
result.put(ResponseConstant.RESPONSE_MSG, "系统繁忙,请稍后重试");
this.writeData(result, response);
} finally {
IOUtils.closeQuietly(in);
}
}