C# 操作阿里云对象存储OSS对图片进行上传、删除操作

一、获取对象存储OSS的AccessKey

在控制台对象存储网页中找到右上角的用户信息,点击“AccessKey管理”(下图)
在这里插入图片描述
进入到安全信息管理(也就是保存AccessKey的)界面(下图),如果没有AccessKey,需要自己创建。
在这里插入图片描述
存储空间可以手动创建,也可以通过代码创建,在该文章中,使用了手动创建,所以没有存储空间创建部分代码。

C#代码操作OSS

一、添加Aliyun.OSS.SDK

在Visual Studio中的Nuget程序包管理器中下载该程序包。(如下图)
在这里插入图片描述

二、代码实现

OssUtil.cs

using Aliyun.OSS;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Security.Policy;
using System.Web;
using System.Web.Security;
using System.Windows.Forms;

/// <summary>
/// OssUtil 的摘要说明
/// </summary>
public class OssUtil
{
        public static string endpoint = "oss-cn-beijing.aliyuncs.com";
        public static string accessKeyId = "accessKeyId ";
        public static string accessKeySecret = "accessKeySecret";
        public static string bucketName = "bucketName";
        public static string objectName = "";
        public static string localFilename = "上传的图片路径";//用于测试,后续可以根据需求修改或弃用
    	public static string tempName = "";
     创建OSSClient实例
    public static OssClient getOSSClient()
    {
        OssClient client = new OssClient(endpoint, accessKeyId, accessKeySecret);
        return client;
    }
    //修改上传文件在对象存储中的Content-Type
    public static String getContentType(String fileName)
    {
        String fileExtension = fileName.Substring(fileName.LastIndexOf(".") + 1);//获取文件扩展名
        if ("bmp".Equals(fileExtension)) return "image/bmp";
        
        if ("gif".Equals(fileExtension)) return "image/gif";
        
        if ("jpeg".Equals(fileExtension) || "jpg".Equals(fileExtension) || "png".Equals(fileExtension)) return "image/jpg";//图片类型如果设置成image/jpeg,会导致预览失败
        
        if ("html".Equals(fileExtension)) return "text/html";
        
        if ("txt".Equals(fileExtension)) return "text/plain";
        
        if ("vsd".Equals(fileExtension)) return "application/vnd.visio";
        
        if ("ppt".Equals(fileExtension) || "pptx".Equals(fileExtension)) return "application/vnd.ms-powerpoint";

        if ("doc".Equals(fileExtension) || "docx".Equals(fileExtension)) return "application/msword";

        if ("pdf".Equals(fileExtension) || "docx".Equals(fileExtension)) return "application/pdf";

        if ("mp3".Equals(fileExtension) || "docx".Equals(fileExtension)) return "audio/mp3";

        if ("xml".Equals(fileExtension)) return "text/xml";

        return "text/html";
    }
    ///<summary>
    ///创建一个指定长度的随机salt值
    /// </summary>
    public static string CreateSalt(int saltLength)
    {
        //生成一个加密的随机数
        RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
        byte[] buff = new byte[saltLength];
        rng.GetBytes(buff);
        //返回一个Base64随机数的字符串
        return Convert.ToBase64String(buff);
    }
    ///<summary>
    ///返回加密后的字符串,作为文件名
    /// </summary>
    /// 
    public static string CreatePasswordHash(string pwd, int saltlength)
    {
        string strSalt = CreateSalt(saltlength);
        //把密码和salt连起来
        string saltAndPwd = String.Concat(pwd, strSalt);
        //对密码进行哈希
        string hashenPwd = FormsAuthentication.HashPasswordForStoringInConfigFile(saltAndPwd, "sha1");
        //转为小写字母并截取前16个字符串
        hashenPwd = hashenPwd.ToLower().Substring(0, 16);
        //返回哈希后的值
        return hashenPwd;
    }

    //上传图片
    public static bool uploadImage(string localFilename)
    {
        OssClient client = getOSSClient();//创建OssClient实例
        try
        {
            string filename = localFilename.Substring(localFilename.LastIndexOf("\\") + 1);//获取图片名
            string fileEx = filename.Substring(filename.LastIndexOf(".") + 1);//获取图片扩展名.jpg

            ObjectMetadata metadata = new ObjectMetadata();
            metadata.ContentLength = 10000;
            metadata.CacheControl = "no-cache";
            metadata.AddHeader("Pragma", "no-cache");
            metadata.ContentEncoding = "utf-8";
            metadata.ContentType = getContentType(filename);
            objectName = "images/" + filename;//"images"是自己创建的一个存储空间下的文件夹,将图片上传到该文件夹里
            tempName = filename;//测试时保存文件名用于后续预览
            var result = client.PutObject(bucketName, objectName, localFilename, metadata);//上传
            Console.WriteLine("Put object succeeded, ETag: {0} ", result.ETag);
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
            Console.WriteLine("Put object failed, {0}", ex.Message);
        }
        return true;
    }

    //浏览图片
    public static string getShowUrl(String tempName)
    {
        string objectKey = tempName;
        string status = "";
        string fileExtension = filepath.Substring(filepath.LastIndexOf(".") + 1);
        if (fileExtension.Equals("jpg") || fileExtension.Equals("jpeg") || fileExtension.Equals("png"))
        {
            status = "";
        }
        else
            status = "imm/previewdoc";
        string url = getUrl(status, accessKeyId, accessKeySecret, bucketName, objectKey);
        return url;
    }

    //获取图片在oss上的预览路径
    private static string getUrl(string process, string ak, string sk, string bucketName, string objectKey)
    {
        OssClient client1 = getOSSClient();
        GetObjectRequest getObjectRequest = new GetObjectRequest(bucketName, objectKey);
        getObjectRequest.Process = process;
        GeneratePresignedUriRequest request = new GeneratePresignedUriRequest(bucketName, objectKey);
        request.Process = process;
        request.Expiration = new DateTime(new DateTime().Minute + 3600 * 1000);
        string str = "https://image2storage.oss-cn-beijing.aliyuncs.com";
        str = str + client1.GeneratePresignedUri(request).AbsolutePath;//这里是返回的预览路径拼接
        Url u = new Url(str);
        return str;
    }

    //删除图片
    public static string deleteImage(string fileName)
    {
        OssClient client = getOSSClient();
             client.DeleteObject(bucketName,"images/"+fileName);
        return "ok";
    }
}

test.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="test.aspx.cs" Inherits="test" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    
<script type="text/javascript" src="js/jquery.js"></script>
    <title>图片上传测试</title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <span class="" id="editor" style="width:800px;margin-left:10px;"></span>
        </div>
        <asp:Button ID="Button2" runat="server" Text="Button" />
        <br />
    <div >
       <asp:FileUpload ID="imgUpload" runat="server" /><input type="hidden" id="txtFilePath" runat="server" />
        <asp:Button ID="Button1" runat="server" Text="上传图片" OnClick="Button1_Click" />
    &nbsp;<br />
        <br />
        <asp:TextBox ID="imgName" runat="server"></asp:TextBox>
        <asp:Button ID="show" runat="server" Text="预览" OnClick="show_Click" />
        <asp:Button ID="del" runat="server" Text="删除" OnClick="del_Click" />
        <br />
        <asp:Image ID="img" runat="server" />
        
    </div>
    </form>
</body>
</html>

页面效果图:(丑不要紧,意思在就行哈)
在这里插入图片描述

text.aspx.cs


using System;
using System.IO;
using System.Web.Services;

public partial class test: System.Web.UI.Page
{

    string localFilename = "测试的图片路径(可要可不要)";
    public static string  name= "";
    protected void Page_Load(object sender, EventArgs e)
    {
    }

    //上传图片
    protected void Button1_Click(object sender, EventArgs e)
    {
        string filePath="";
        if (imgUpload.HasFile)//验证是否包含文件
        {
            //取得文件的扩展名,并转换成小写
            string fileExtension = Path.GetExtension(imgUpload.FileName).ToLower();
            
                //对上传文件的大小进行检测,限定文件最大不超过8M
                if (imgUpload.PostedFile.ContentLength < 8192000)
                {
                    string filepath = "/images/";
                    if (Directory.Exists(Server.MapPath(filepath)) == false)
                    {
                        Directory.CreateDirectory(Server.MapPath(filepath));
                    }
                    //没有实现直接在浏览器中获取图片在电脑里的本地路径,所以把服务器当做中转来上传图片
                    string virpath = filepath + OssUtil.CreatePasswordHash(imgUpload.FileName, 4) + fileExtension;//这是存到当前项目服务器上的虚拟路径
                    string mappath = Server.MapPath(virpath);//转换成服务器上的物理路径
                    imgUpload.PostedFile.SaveAs(mappath);//保存图片
                    filePath = mappath;
                    OssUtil.uploadImage(filePath);
                    this.imgName.Text = OssUtil.tempName;//将当前上传的图片名回填到前端textbox里

                    //上传完成后删除服务器上保存的该图片
                    System.IO.File.Delete(Server.MapPath(virpath));
                }
           }
    }
 
    //预览图片,显示在前端Image控件里
    protected void show_Click(object sender, EventArgs e)
    {
        string imageName = this.imgName.Text;
        string url = OssUtil.getShowUrl("images/"+imageName);
        img.ImageUrl = url;
    }

   //删除
    protected void del_Click(object sender, EventArgs e)
    {
        string image = this.imgName.Text;
        OssUtil.deleteImage(image);
    }
}

运行效果图:上传成功后进行浏览
在这里插入图片描述
完整的C#操作阿里云对象存储的步骤就到这里就结束啦,如果该文章哪些部分写得有错误,还请大家多多指教。抱拳感谢!

附上参考的资料:
C# .net 实现图片上传功能:https://www.cnblogs.com/dingfangbo/p/5769949.html
C#实现上传和显示图片:https://www.jb51.net/article/95408.htm

  • 2
    点赞
  • 2
    评论
  • 8
    收藏
  • 打赏
    打赏
  • 扫一扫,分享海报

©️2022 CSDN 皮肤主题:深蓝海洋 设计师:CSDN官方博客 返回首页

打赏作者

陈同学是个程序员

你的鼓励将是我创作的最大动力

¥2 ¥4 ¥6 ¥10 ¥20
输入1-500的整数
余额支付 (余额:-- )
扫码支付
扫码支付:¥2
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值