go 阿里云oss上传

作者: adm 分类: go 发布时间: 2023-09-01
func (e Aliyun)UploadFile2(c *gin.Context) (returnPdf ReturnPdf, err error)  {

	/*
	   通过form-data上传文件,文件名:file
	*/
	file,err := c.FormFile("file")
	if err != nil {
		return returnPdf,err
	}

	fileHandle,err := file.Open()   //打开上传文件
	if err != nil {
		return returnPdf,err
	}
	defer fileHandle.Close()
	fileByte,err :=  ioutil.ReadAll(fileHandle)  //获取上传文件字节流
	if err != nil {
		return returnPdf,err
	}

	url,err := Upload(file.Filename,fileByte,path.Ext(file.Filename))
	returnPdf.Url= url
	returnPdf.Name= url

	return returnPdf,nil
}

func Upload(fileName string,fileByte []byte,ext string)(url string,err error)  {
	/*
	   oss 的相关配置信息
	*/
	bucketName := "xxx"
	endpoint := "xxx"
	accessKeyId := "xxx"
	accessKeySecret := "xxx"
	domain := "xxx"


	//创建OSSClient实例
	client, err := oss.New(endpoint, accessKeyId, accessKeySecret)
	if err != nil {
		return url,err
	}

	// 获取存储空间
	bucket, err := client.Bucket(bucketName)
	if err != nil {
		return url,err
	}
	//文件重命名
	file_name := strconv.FormatInt(time.Now().Unix(), 10) + strconv.Itoa(rand.Intn(999999-100000)+100000)+ext
	//上传阿里云路径
	folderName := time.Now().Format("20060102")
	yunFileTmpPath := "pdf/"+folderName + "/" + file_name  //uploads/2020-06-17/GoLang (1).docx

	// 上传Byte数组
	err = bucket.PutObject(yunFileTmpPath, bytes.NewReader([]byte(fileByte)))
	if err != nil {
		return url,err
	}


	return domain + "/" + yunFileTmpPath ,nil
}

如果觉得我的文章对您有用,请随意赞赏。您的支持将鼓励我继续创作!