问题原因
OSS在上传文件时默认的文件请求头信息为application/octet-stream(字节流)
所以浏览器在访问的时候并不知道文件类型,所以读取字节流就相当于下载文件到本地了。
修改逻辑,上传文件时指定文件请求头信息即可
修改代码很简单,在上传文件的时候告知oss文件类型即可
com.aliyun.oss.model.ObjectMetadata metadata = new com.aliyun.oss.model.ObjectMetadata();
for (int i = 0; i < file.length; i++) {
//文件类型一般为 image/jpeg
metadata.setContentType(file[i].getContentType());
InputStream is = file[i].getInputStream();
String fileKey = AppUploader.getOssKey(bussinessType,file[i].getOriginalFilename());
OSSConfig.OSS_CLIENT.putObject(OSSConfig.OSS_DIGITAL_BUCKET_NAME,fileKey,is,metadata);
is.close();
}
如果已经有很多的图片文件没有按这种方式上传导致问题严重可以参考
//OSS设置文件HTTP头
https://help.aliyun.com/document_detail/31913.html
//通过命令批量修改oss文件请求头信息
https://help.aliyun.com/document_detail/120056.htm?spm=a2c4g.11186623.2.4.5928401cAPOqwP#concept-303809
如果图片需要下载怎么办
@RequestMapping(value = "/uploader/main/download",method = RequestMethod.GET)
public String uploaderMainDownload(String key, HttpServletResponse response){
if (ObjectUtils.isEmpty(key)){
return JSON.toJSONString(MsgOut.error("key - null"));
}
InputStream downloadStream = null;
OSSObject ossObject = null;
try{
boolean exists = OSSConfig.OSS_CLIENT.doesObjectExist(OSSConfig.OSS_DIGITAL_BUCKET_NAME,key);
if (!exists){
return renderJson(MsgOut.error("文件不存在"));
}
ossObject = OSSConfig.OSS_CLIENT.getObject(OSSConfig.OSS_DIGITAL_BUCKET_NAME,key);
if (!ObjectUtils.isEmpty(ossObject)){
downloadStream = ossObject.getObjectContent();
}
if (ObjectUtils.isEmpty(ossObject) || ObjectUtils.isEmpty(downloadStream)){
return renderJson(MsgOut.error("文件不存在"));
}
int buffer = 1024 * 10;
byte data[] = new byte[buffer];
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(key,"UTF-8"));//将文件名转为ASCLL编码
int read;
while ((read = downloadStream.read(data)) != -1) {
response.getOutputStream().write(data, 0, read);
}
response.getOutputStream().flush();
response.getOutputStream().close();
return this.renderJson(MsgOut.success());
}catch (Exception e){
e.printStackTrace();
return JSON.toJSONString(MsgOut.error());
}finally {
try {
if (downloadStream != null){
downloadStream.close();
}
if (ossObject != null) {
ossObject.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}