package life.majiang.community.community.controller;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.CannedAccessControlList;
import com.aliyun.oss.model.PutObjectRequest;
import life.majiang.community.community.dto.FileDTO;
import life.majiang.community.community.util.AliyunOssConfigConstant;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.UUID;
/**
* 处理文件上传
*/
@Controller
public class FileController {
private static String bucketName = AliyunOssConfigConstant.BUCKE_NAME;
private static String endPoint = AliyunOssConfigConstant.END_POINT;
private static String accessKeyId = AliyunOssConfigConstant.AccessKey_ID;
private static String accessKeySecret = AliyunOssConfigConstant.AccessKey_Secret;
private static String fileHost = AliyunOssConfigConstant.FILE_HOST;
@ResponseBody
@RequestMapping("/file/upload")
public FileDTO upload(HttpServletRequest request){
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest)request;
MultipartFile file = multipartRequest.getFile("editormd-image-file");
String realPath = System.getProperty("user.dir");
realPath+="\\target\\classes\\static\\images\\";//uploadFile
System.out.println(realPath);
File folder = new File(realPath);
if(!folder.isDirectory()){
//文件夹不存在,创建
folder.mkdirs();
}
OSS ossClient = new OSSClientBuilder().build(endPoint,accessKeyId ,accessKeySecret);
//文件重命名
String oldFile = file.getOriginalFilename();
String newFile = UUID.randomUUID().toString()+oldFile.substring(oldFile.lastIndexOf("."),oldFile.length());
String url;
FileDTO fileDTO = null;
try {
//保存文件
file.transferTo(new File(folder,newFile));
//拼接url
url = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+"/images/"+newFile;
fileDTO = new FileDTO();
fileDTO.setSuccess(1);
fileDTO.setUrl(url);
PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, url, new File("/images/"));
ossClient.putObject(putObjectRequest);
return fileDTO;
}catch (Exception e){
fileDTO.setSuccess(0);
e.printStackTrace();
}finally {
ossClient.shutdown();
}
return null;
}
}
上传到oss名字虽然不一样,但都是同一张图片。 java保存到文件图片没问题,就是上传到oss的图片都是同一张。
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。