阿里云OSS使用——java中图片上传返回url(Spring Boot项目中详细使用)--菜鸟小回

阿里云OSS使用——java中图片上传返回url(Spring Boot项目中详细使用)


一、开通阿里云oss服务阿里云oss服务

二、基本配置参见小书匠绑定阿里云oss

三、controller

    /**
     * 上传图片到 oss
     * @param imgFile
     * @return
     */
    @ApiOperation(value = "上传图片到oss")
    @PostMapping(value="/uploadImgToOSS")
    public String uploadImgToOSS(MultipartFile imgFile) {
        return ossUploadImage.uploadImg(imgFile);
    }

四、工具类

@Component
public class OssUploadImage {

	protected static final Logger log = LoggerFactory.getLogger(OssUploadImage.class);
	@Value("${Oos.endpoint}")
	private String endpoint;
	@Value("${Oos.accessKeyId}")
	private String accessKeyId;
	@Value("${Oos.accessKeySecret}")
	private String accessKeySecret;
	@Value("${Oos.bucketName}")
	private String bucketName;
	@Value("${Oos.filedir}")
	private String filedir;

	/**
	 *
	 * 上传图片
	 * @param file
	 * @return
	 */
	public  String uploadImg2Oss(MultipartFile file) {
		if (file.getSize() > 1024 * 1024 *20) {
			//RestResultGenerator.createErrorResult(ResponseEnum.PHOTO_TOO_MAX);
			return "图片太大";
		}
		String originalFilename = file.getOriginalFilename();
		String substring = originalFilename.substring(originalFilename.lastIndexOf(".")).toLowerCase();
		Random random = new Random();
		String name = random.nextInt(10000) + System.currentTimeMillis() + substring;
		try {
			InputStream inputStream = file.getInputStream();
			//RestResultGenerator.createSuccessResult(name);
			this.uploadFile2OSS(inputStream, name);
			return name;
		} catch (Exception e) {
			//RestResultGenerator.createErrorResult(ResponseEnum.PHOTO_UPLOAD);
			return "上传失败";
		}
	}

	/**
	 * 上传图片获取fileUrl
	 * @param instream
	 * @param fileName
	 * @return
	 */
	private String uploadFile2OSS(InputStream instream, String fileName) {
		String ret = "";
		try {
			//创建上传Object的Metadata
			ObjectMetadata objectMetadata = new ObjectMetadata();
			objectMetadata.setContentLength(instream.available());
			objectMetadata.setCacheControl("no-cache");
			objectMetadata.setHeader("Pragma", "no-cache");
			objectMetadata.setContentType(getcontentType(fileName.substring(fileName.lastIndexOf("."))));
			objectMetadata.setContentDisposition("inline;filename=" + fileName);
			//上传文件

			OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
			PutObjectResult putResult = ossClient.putObject(bucketName, filedir + fileName, instream, objectMetadata);
			ret = putResult.getETag();
		} catch (IOException e) {
			log.error(e.getMessage(), e);
		} finally {
			try {
				if (instream != null) {
					instream.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return ret;
	}

	public static String getcontentType(String FilenameExtension) {
		if (FilenameExtension.equalsIgnoreCase(".bmp")) {
			return "image/bmp";
		}
		if (FilenameExtension.equalsIgnoreCase(".gif")) {
			return "image/gif";
		}
		if (FilenameExtension.equalsIgnoreCase(".jpeg") ||
				FilenameExtension.equalsIgnoreCase(".jpg") ||
				FilenameExtension.equalsIgnoreCase(".png")) {
			return "image/jpg";
		}
		if (FilenameExtension.equalsIgnoreCase(".html")) {
			return "text/html";
		}
		if (FilenameExtension.equalsIgnoreCase(".txt")) {
			return "text/plain";
		}
		if (FilenameExtension.equalsIgnoreCase(".vsd")) {
			return "application/vnd.visio";
		}
		if (FilenameExtension.equalsIgnoreCase(".pptx") ||
				FilenameExtension.equalsIgnoreCase(".ppt")) {
			return "application/vnd.ms-powerpoint";
		}
		if (FilenameExtension.equalsIgnoreCase(".xls") ||
				FilenameExtension.equalsIgnoreCase(".xlsx")) {
			return "application/vnd.ms-excel";
		}
		if (FilenameExtension.equalsIgnoreCase(".docx") ||
				FilenameExtension.equalsIgnoreCase(".doc")) {
			return "application/msword";
		}
		if (FilenameExtension.equalsIgnoreCase(".xml")) {
			return "text/xml";
		}
		return "image/jpg";
	}

	/**
	 * 获取图片路径
	 * @param fileUrl
	 * @return
	 */
	public String getImgUrl(String fileUrl) {
		if (fileUrl!=null) {
			String[] split = fileUrl.split("/");
			String url =  this.getUrl(this.filedir + split[split.length - 1]);
			return url;
		}
		return null;
	}

	/**
	 * 获得url链接
	 *
	 * @param key
	 * @return
	 */
	public String getUrl(String key) {
		// 设置URL过期时间为10年  3600l* 1000*24*365*10
		Date expiration = new Date(new Date().getTime() + 3600l * 1000 * 24 * 365 * 10);
		// 生成URL
		OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
		URL url = ossClient.generatePresignedUrl(bucketName, key, expiration);
		if (url != null) {
			return url.toString();
		}
		return null;
	}


	/**
	 * 多图片上传
	 * @param fileList
	 * @return
	 */
	public String checkList(List fileList) {
		String  fileUrl = "";
		String  str = "";
		String  photoUrl = "";
		for(int i = 0;i< fileList.size();i++){
			fileUrl = uploadImg2Oss(fileList.get(i));
			str = getImgUrl(fileUrl);
			if(i == 0){
				photoUrl = str;
			}else {
				photoUrl += "," + str;
			}
		}
		return photoUrl.trim();
	}

	/**
	 * 单个图片上传
	 * @param file
	 * @return
	 */
	public  String uploadImg(MultipartFile file){
		String fileUrl = uploadImg2Oss(file);
		String str = getImgUrl(fileUrl);
		return str.trim();
	}
}

五、application.properties

配置获取位置参见小书匠绑定阿里云oss

#oss配置
Oos.endpoint=oss-cn-hangzhou.aliyuncs.com
Oos.accessKeyId=LTA***RHffBc
Oos.accessKeySecret=pMWwp***AVheTs
Oos.bucketName=idse-oss
Oos.filedir=image/

六、前端

  1. html
等待上传
  1. ajax提交
//上传图片
function upLoadImg(){
    $("#imgFile").live("change",function(){
        //注意这里不能写错。。。
        var file=$("#imgFile")[0].files[0];
        var formData = new FormData();
        formData.append("imgFile",file);
        //对文件类型进行判断
        var index=file.name.lastIndexOf(".");
        var type=file.name.substring(index);
        if(type!=".jpg"&&type!=".png"){
            alert("只能上传jpg和png格式的图片!!");
            return;
        }
        $.ajax({
            url:"../uploadImgToOSS",
            data:formData,
            dataType:"text",
            type:"post",
            //这两个属性必须设置!!!!
            contentType: false,
            processData: false, //设置为true时,ajax提交的时候不会序列化data,而是直接使用data
            success:function (path) {
                $("#yulan").attr("src",path);
                $("input[name='imgUrl']").attr("value",path);
            }
        })
    })
}

七、文件上传类似,把后缀限制去掉就可以了。

你可能感兴趣的:(日常技术,Java技术)