文件上传
service
public String saveImage(MultipartFile file) throws IOException {
// 正确性检验
int dotPos = file.getOriginalFilename().lastIndexOf(".");
if (dotPos < 0) {
return null;
}
String fileExt = file.getOriginalFilename().substring(dotPos + 1).toLowerCase();
if (!ToutiaoUtil.isFileAllowed(fileExt)) {
return null;
}
//给文件取一个新的名字
String fileName = UUID.randomUUID().toString().replaceAll("-", "") + "." + fileExt;
Files.copy(file.getInputStream(), new File(ToutiaoUtil.IMAGE_DIR + fileName).toPath(),
StandardCopyOption.REPLACE_EXISTING);
return ToutiaoUtil.TOUTIAO_DOMAIN + "image?name=" + fileName;
}
ToutiaoUtil
public static String TOUTIAO_DOMAIN = "http://127.0.0.1:8080/";
public static String IMAGE_DIR = "D:/upload/";
public static String[] IMAGE_FILE_EXTD = new String[] {"png", "bmp", "jpg", "jpeg"};
public static boolean isFileAllowed(String fileName) {
for (String ext : IMAGE_FILE_EXTD) {
if (ext.equals(fileName)) {
return true;
}
}
return false;
}
关于StandardCopyOption的选项
有三个选择,分别是
ATOMIC_MOVE
Move the file as an atomic file system operation.
解释:
copy() 方法不支持StandardCopyOption的ATOMIC_MOVE选项,在文件拷贝中该选项是一个无意义的。
用于文件的原子性移动操作,要么移动成功,要么不用移动。
|
COPY_ATTRIBUTES
Copy attributes to the new file.
解释:
尝试将文件的属性拷贝到目标文件。
|
REPLACE_EXISTING
Replace an existing file if it exists.
解释:当文件已经存在时,目标文件将被代替。
|
使用七牛云存储图片
@Service
public class QiniuService {
private static final Logger logger = LoggerFactory.getLogger(QiniuService.class);
//设置好账号的ACCESS_KEY和SECRET_KEY
String ACCESS_KEY = "abNXnXBIlI6viRaOeRY6Hk-zc3V-NpjLcGfYz5kD";
String SECRET_KEY = "QP7Xja3FmP1Zyl-oxwQDCb7T6wCoEFKoO-0vht_5";
//要上传的空间
String bucketname = "nowcoder";
//密钥配置
Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
//创建上传对象
UploadManager uploadManager = new UploadManager();
private static String QINIU_IMAGE_DOMAIN = "http://7xsetu.com1.z0.glb.clouddn.com/";
//简单上传,使用默认策略,只需要设置上传的空间名就可以了
public String getUpToken() {
return auth.uploadToken(bucketname);
}
public String saveImage(MultipartFile file) throws IOException {
try {
int dotPos = file.getOriginalFilename().lastIndexOf(".");
if (dotPos < 0) {
return null;
}
String fileExt = file.getOriginalFilename().substring(dotPos + 1).toLowerCase();
if (!ToutiaoUtil.isFileAllowed(fileExt)) {
return null;
}
String fileName = UUID.randomUUID().toString().replaceAll("-", "") + "." + fileExt;
//调用put方法上传
Response res = uploadManager.put(file.getBytes(), fileName, getUpToken());
//打印返回的信息
if (res.isOK() && res.isJson()) {
return QINIU_IMAGE_DOMAIN + JSONObject.parseObject(res.bodyString()).get("key");
} else {
logger.error("七牛异常:" + res.bodyString());
return null;
}
} catch (QiniuException e) {
// 请求失败时打印的异常的信息
logger.error("七牛异常:" + e.getMessage());
return null;
}
}
}
文件下载
@RequestMapping(path = {"/image"}, method = {RequestMethod.GET})
@ResponseBody
public void getImage(@RequestParam("name") String imageName,
HttpServletResponse response) {
try {
response.setContentType("image/jpeg");
StreamUtils.copy(new FileInputStream(new
File(ToutiaoUtil.IMAGE_DIR + imageName)), response.getOutputStream());
} catch (Exception e) {
logger.error("读取图片错误" + imageName + e.getMessage());
}
}