文件上传接口中应该判断文件类型是否为图片
crazyjavar opened this issue · 1 comments
UploadController的upload方法。修改后的代码
package cn.exrick.xboot.modules.base.controller.common;
import cn.exrick.xboot.common.utils.Base64DecodeMultipartFile;
import cn.exrick.xboot.common.utils.QiniuUtil;
import cn.exrick.xboot.common.utils.ResultUtil;
import cn.exrick.xboot.common.vo.Result;
import cn.hutool.core.io.FileTypeUtil;
import cn.hutool.core.util.StrUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.InputStream;
/**
-
@author Exrickx
*/
@slf4j
@RestController
@Api(description = "文件上传接口")
@RequestMapping("/xboot/upload")
@transactional
public class UploadController {@Autowired
private QiniuUtil qiniuUtil;@RequestMapping(value = "/file", method = RequestMethod.POST)
@ApiOperation(value = "文件上传")
public Result upload(@RequestParam(required = false) MultipartFile file,
@RequestParam(required = false) String base64,
HttpServletRequest request) {if (StrUtil.isNotBlank(base64)) { // base64上传 file = Base64DecodeMultipartFile.base64Convert(base64); } String result = null; String fileName = qiniuUtil.renamePic(file.getOriginalFilename()); try { InputStream inputStream = file.getInputStream(); String type = FileTypeUtil.getType(inputStream); if (type == null) { return new ResultUtil<>().setErrorMsg("上传类型不是图片类型"); } //上传七牛云服务器 result = qiniuUtil.qiniuInputStreamUpload(inputStream, fileName); } catch (Exception e) { log.error(e.toString()); return new ResultUtil<Object>().setErrorMsg(e.toString()); } return new ResultUtil<Object>().setData(result);
}
}
这是通用文件上传接口...不仅是图片