• 多媒体文件上传(一)


    一个多媒体图片上传的功能(winform),web同理,本例子实现存储路径至数据库

    实现思路,用户上传本地多媒体数据至服务端,服务端接收用户传递的数据,在服务器上建立一个存储文件夹,存储用户多媒体数据,数据库存储数据在服务器上的绝对路径

    一、先在服务器上建立一个文件上传后保存的路径文件夹,然后在代码config里配置一下

     <!--文件上传保存路径-->
        <add key="saveFileFolder" value="D:多媒体数据" />

    二、获取照片的一些信息(FileUploadDTO)

    using System;
    
    namespace Media
    {
        public class FileUploadDTO
        {
            /// <summary>
            /// 文件名
            /// </summary>
            public string name;/// <summary>
            /// 文件大小
            /// </summary>
            public int size;/// <summary>
            /// 扩展名 例:".txt"
            /// </summary>
            public string ext;

              /// <summary>
              /// 文件路径
             /// </summary>

    public string SAVEPATH;//传递的字节数
            public byte[] Data;
        }
    }

    三、存入数据库的信息(FileImageDTO)

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace Media
    {
      public  class FileImageDTO
        {
            /// <summary>
            /// 文件名
            /// </summary>
            public string name { get; set; }
            /// <summary>
            /// 服务器上文件名
            /// </summary>
            public string FILENAME { get; set; }
            /// <summary>
            /// 描述名
            /// </summary>
            public string FILEDESC { get; set; }
            /// <summary>
            /// 文件主键
            /// </summary>
            public string GUID { get; set; }
            /// <summary>
            /// 文件扩展名
            /// </summary>
            public string FILEEXTNAME { get; set; }
            /// <summary>
            /// 创建时间
            /// </summary>
            public System.DateTime CREATEDDATE { get; set; }
            /// <summary>
            /// 文件保存路径
            /// </summary>
            public string SAVEPATH { get; set; }
        }
    }

    四、多媒体上传帮助类(Mediaupload)

    using System;
    using System.Collections.Generic;
    using System.Data;
    using System.IO;
    using System.Linq;
    using System.Runtime.Remoting.Messaging;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace Media
    {
      public  class Mediaupload
        {
            public void segmentReadUpload(FileUploadDTO file)
            {
                string filePath = System.Configuration.ConfigurationManager.AppSettings["saveFileFolder"];//指定文件上传位置
                FileImageDTO dto = new FileImageDTO();
                if (file.Offset == 0)//第一次传入文件
                {
                    DateTime dateTime = DateTime.Now;
                    dto.name = file.name;//文件名
                   filePath = Path.Combine(filePath, "uploadFiles", dateTime.ToString("yyyy-MM-dd"));//上传后文件在服务器上存放文件文件夹的路径
                    checkDIR(filePath);
                    dto.FILENAME = Guid.NewGuid().ToString() + file.ext;//上传至服务器后文件的名称
                    filePath = Path.Combine(filePath, dto.FILENAME);             
                    dto.CREATEDDATE = dateTime;//上传时间
                    dto.GUID = Guid.NewGuid().ToString();//文件唯一识别
                    dto.FILEEXTNAME = file.ext;//文件扩展名
                    dto.SAVEPATH = filePath;//上传后文件在服务器上的路径              
               }
                FileStream fs = new FileStream(filePath, FileMode.OpenOrCreate);//打开文件
               long offset = file.Offset;  //file.Offset 文件偏移位置,表示从这个位置开始进行后面的数据添加
                BinaryWriter writer = new BinaryWriter(fs);//初始化文件写入器
                writer.Seek((int)offset, SeekOrigin.Begin);//设置文件的写入位置
                writer.Write(file.Data);//写入数据
               file.Offset = fs.Length;//返回追加数据后的文件位置
                file.Data = null;
                Upload(dto);//信息写入数据库
                writer.Close();
                fs.Close();
            }
          
            //检查目录,如果不存在则创建
            private void checkDIR(string path)
            {
                if (!Directory.Exists(path))
                    Directory.CreateDirectory(path);
            }
            public void Upload(FileImageDTO DTO)
            {
                //  StringBuilder sql = new StringBuilder();
                string sql = string.Format("INSERT INTO FILEIMAGE(NAME,FILENAME,FILEDESC,GUID,FILEEXTNAME,SAVEPATH,CREATEDDATE) VALUES('{0}','{1}','{2}','{3}','{4}','{5}',to_date('{6}','yyyy-mm-dd hh24:MI:SS'))",DTO.name,DTO.FILENAME,DTO.FILEDESC,DTO.GUID,DTO.FILEEXTNAME,DTO.SAVEPATH,DTO.CREATEDDATE);
                SqlHelper.ExecuteNonQuery(sql, CommandType.Text, null);//增加
    
            }
        }
    }

    五、点击上传操作

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Drawing.Imaging;
    using System.IO;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Windows.Forms;
    
    namespace Media
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }
    
            private void button1_Click(object sender, EventArgs e)
            {
                FileUploadDTO dt = new FileUploadDTO();
                OpenFileDialog f1 = new OpenFileDialog();
                f1.Title = "文件上传";
                f1.Filter = "All Files|*.*|课件(*.ppt)|*.ppt|教学大纲和授课计划(*.doc)|*.doc";          
                if (f1.ShowDialog() == DialogResult.OK)
                {
                    FileInfo fileInfo = new FileInfo(f1.FileName);               
                    dt.name = fileInfo.Name;//文件名称
                    dt.ext = fileInfo.Extension;//扩展名
                    dt.size = (int)fileInfo.Length;//文件大小
                    Image image = Image.FromFile(fileInfo.FullName);
                   // Bitmap bitmap = new Bitmap(f1.FileName);
                    dt.Data = ImageToBytes(image);             
                    Mediaupload _fi = new Mediaupload();
                    _fi.segmentReadUpload(dt);
                }            
            }
            /// <summary>
            /// 将照片转为byte[]
            /// </summary>
            /// <param name="image"></param>
            /// <returns></returns>
            public static byte[] ImageToBytes(Image image)
            {
                ImageFormat format = image.RawFormat;
                using (MemoryStream ms = new MemoryStream())
                {
                    image.Save(ms, format);
                    return ms.ToArray();
                }
            }
        }
    }

    六、oracle数据库帮助类

    using System;
    using System.Collections.Generic;
    using System.Data;
    using System.Data.OracleClient;
    using System.Linq;
    using System.Reflection;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace Media
    {
     public  class SqlHelper
        {
            #region 样本
            //标准连接
         private static readonly string defaultConnectString = "Data Source=******;User Id=*****;Password=****;";
            //标准链接
            #endregion
            #region 变量
            private static OracleConnection _con = null;
            public static string _constr = "Data Source=******;User Id=*****;Password=****;";
    
            #endregion
    
    
            #region 属性
    
            public static string constr
            {
                get
                {
                    if (_constr == null || _constr.Equals(String.Empty))
                    {
                        _constr = defaultConnectString;
                    }
                    return _constr;
                }
                set
                {
                    _constr = value;
                }
            }
    
            /// <summary>  
            /// 获取或设置数据库连接对象  
            /// </summary>  
            public static OracleConnection Con
            {
                get
                {
    
                    if (SqlHelper._con == null)
                    {
                        SqlHelper._con = new OracleConnection();
                    }
                    if (SqlHelper._con.ConnectionString == null || SqlHelper._con.ConnectionString.Equals(string.Empty))
                    {
                        SqlHelper._con.ConnectionString = SqlHelper.constr;
                    }
                    return SqlHelper._con;
                }
                set
                {
                    SqlHelper._con = value;
                }
            }
            #endregion
    
            #region 方法
    
            /// <summary>    
            /// 执行并返回第一行第一列的数据库操作  
            /// </summary>  
            /// <param name="commandText">Sql语句或存储过程名</param>  
            /// <param name="commandType">Sql命令类型</param>  
            /// <param name="param">Oracle命令参数数组</param>  
            /// <returns>第一行第一列的记录</returns>  
            public static int ExecuteScalar(string commandText, CommandType commandType, params OracleParameter[] param)
            {
                int result = 0;
                try
                {
                    using (OracleCommand cmd = new OracleCommand(commandText, SqlHelper.Con))
                    {
                        try
                        {
                            cmd.CommandType = commandType;
                            if (param != null)
                            {
                                cmd.Parameters.AddRange(param);
                            }
                            SqlHelper.Con.Open();
                            string x = cmd.CommandText;
                            result = Convert.ToInt32(cmd.ExecuteScalar());
                        }
                        catch
                        {
                            result = -1;
                        }
                    }
                }
                finally
                {
                    if (SqlHelper.Con.State != ConnectionState.Closed)
                    {
                        SqlHelper.Con.Close();
                    }
                }
                return result;
            }
    
            /// <summary>  
            /// 执行不查询的数据库操作  
            /// </summary>  
            /// <param name="commandText">Oracle语句或存储过程名</param>  
            /// <param name="commandType">Oracle命令类型</param>  
            /// <param name="param">Oracle命令参数数组</param>  
            /// <returns>受影响的行数</returns>  
            public static int ExecuteNonQuery(string commandText, CommandType commandType, params OracleParameter[] param)
            {
                int result = 0;
                try
                {
                    using (OracleCommand cmd = new OracleCommand(commandText, SqlHelper.Con))
                    {
                        try
                        {
                            //cmd.CommandType = commandType;
                            if (param != null)
                            {
                                cmd.Parameters.AddRange(param);
                            }
                            SqlHelper.Con.Open();
                            result = cmd.ExecuteNonQuery();
                        }
                        catch (Exception ex)
                        {
                            result = -1;
                        }
                    }
                }
                finally
                {
                    if (SqlHelper.Con.State != ConnectionState.Closed)
                    {
                        SqlHelper.Con.Close();
                    }
                }
                return result;
            }
    
            /// <summary>
            /// 获取数据表
            /// </summary>
            /// <param name="commandText">select命令</param>
            /// <param name="param">参数表</param>
            /// <returns></returns>
            public static DataTable GetDataTable(string commandText, params OracleParameter[] param)
            {
                DataTable result = new DataTable();
                try
                {
                    using (OracleCommand cmd = new OracleCommand(commandText, SqlHelper.Con))
                    {
                        if (param != null)
                            cmd.Parameters.AddRange(param);
                        try
                        {
                            OracleDataAdapter adapter = new OracleDataAdapter(cmd);
                            adapter.Fill(result);
                        }
                        catch (Exception ex)
                        {
                            result = null;
                        }
                    }
                }
                finally
                {
                    if (SqlHelper.Con.State != ConnectionState.Closed)
                    {
                        SqlHelper.Con.Close();
                    }
                }
                return result;
            }
    
            public static int GetNextValueInSequence(string sequenceName)
            {
                if (ExecuteScalar("select count(*) from user_objects where OBJECT_NAME=:seqName", CommandType.Text, new OracleParameter(":seqName", sequenceName)) > 0)
                {
                    return ExecuteScalar("select " + sequenceName + ".nextval from dual", CommandType.Text);
                }
                else
                {
                    return -1;
                }
    
    
            }
    
            /// <summary>
            /// 事务模式执行多行非查询语句
            /// </summary>
            /// <param name="commandText">sql语句</param>
            /// <param name="param">参数</param>
            /// <returns>受影响行数</returns>
            public static int ExecuteNonQueryTransaction(string commandText, List<OracleParameter[]> param)
            {
                int result = 0;
                try
                {
                    using (OracleCommand cmd = new OracleCommand(commandText, SqlHelper.Con))
                    {
                        SqlHelper.Con.Open();
                        cmd.Transaction = cmd.Connection.BeginTransaction();
                        try
                        {
                            foreach (OracleParameter[] par in param)
                            {
                                cmd.Parameters.Clear();
                                cmd.Parameters.AddRange(par);
                                result += cmd.ExecuteNonQuery();
                            }
                            cmd.Transaction.Commit();
                        }
                        catch
                        {
                            result = -1;
                            try
                            {
                                cmd.Transaction.Rollback();
                            }
                            catch
                            {
                                result = -2;
                            }
                        }
                    }
                }
                finally
                {
                    if (SqlHelper.Con.State != ConnectionState.Closed)
                    {
                        SqlHelper.Con.Close();
                    }
                }
                return result;
            }
    
    
            /// <summary>   
            /// 执行返回一条记录的泛型对象
            /// </summary>
            /// <typeparam name="T">泛型类型</typeparam>  
            /// <param name="reader">只进只读对象</param>  
            /// <returns>泛型对象</returns>  
            private static T ExecuteDataReader<T>(IDataReader reader)
            {
                T obj = default(T);
                try
                {
                    Type type = typeof(T);
                    obj = (T)Activator.CreateInstance(type);//从当前程序集里面通过反射的方式创建指定类型的对象
                    //obj = (T)Assembly.Load(SqlHelper._assemblyName).CreateInstance(SqlHelper._assemblyName + "." + type.Name);//从另一个程序集里面通过反射的方式创建指定类型的对象
                    PropertyInfo[] propertyInfos = type.GetProperties();//获取指定类型里面的所有属性  
                    foreach (PropertyInfo propertyInfo in propertyInfos)
                    {
                        for (int i = 0; i < reader.FieldCount; i++)
                        {
                            string fieldName = reader.GetName(i);
                            if (fieldName.ToLower() == propertyInfo.Name.ToLower())
                            {
                                object val = reader[propertyInfo.Name];//读取表中某一条记录里面的某一列  
                                if (val != null && val != DBNull.Value)
                                {
                                    Type valType = val.GetType();
    
                                    if (valType == typeof(float) || valType == typeof(double) || valType == typeof(decimal))
                                    {
                                        propertyInfo.SetValue(obj, Convert.ToDouble(val), null);
                                    }
                                    else if (valType == typeof(int))
                                    {
                                        propertyInfo.SetValue(obj, Convert.ToInt32(val), null);
                                    }
                                    else if (valType == typeof(DateTime))
                                    {
                                        propertyInfo.SetValue(obj, Convert.ToDateTime(val), null);
                                    }
                                    else if (valType == typeof(string))
                                    {
                                        propertyInfo.SetValue(obj, Convert.ToString(val), null);
                                    }
                                }
                                break;
                            }
                        }
                    }
                }
                catch
                {
                    throw;
                }
                return obj;
            }
    
            /// <summary>    
            /// 执行返回一条记录的泛型对象  
            /// </summary>  
            /// <typeparam name="T">泛型类型</typeparam>  
            /// <param name="commandText">Oracle语句或存储过程名</param>  
            /// <param name="commandType">Oracle命令类型</param>  
            /// <param name="param">Oracle命令参数数组</param>  
            /// <returns>实体对象</returns>  
            public static T ExecuteEntity<T>(string commandText, CommandType commandType, params OracleParameter[] param)
            {
                T obj = default(T);
                try
                {
                    using (OracleCommand cmd = new OracleCommand(commandText, SqlHelper.Con))
                    {
                        cmd.CommandType = commandType;
                        cmd.Parameters.AddRange(param);
                        SqlHelper.Con.Open();
                        OracleDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
                        while (reader.Read())
                        {
                            obj = SqlHelper.ExecuteDataReader<T>(reader);
                        }
                    }
                }
                finally
                {
                    if (SqlHelper.Con.State != ConnectionState.Closed)
                    {
                        SqlHelper.Con.Close();
                    }
                }
                return obj;
            }
    
            /// <summary>  
            /// 执行返回多条记录的泛型集合对象  
            /// </summary>  
            /// <typeparam name="T">泛型类型</typeparam>  
            /// <param name="commandText">Oracle语句或存储过程名</param>  
            /// <param name="commandType">Oracle命令类型</param>  
            /// <param name="param">Oracle命令参数数组</param>  
            /// <returns>泛型集合对象</returns>  
            public static List<T> ExecuteList<T>(string commandText, CommandType commandType, params OracleParameter[] param)
            {
                List<T> list = new List<T>();
                try
                {
                    using (OracleCommand cmd = new OracleCommand(commandText, SqlHelper.Con))
                    {
                        try
                        {
                            cmd.CommandType = commandType;
    
                            if (param != null)
                            {
                                cmd.Parameters.AddRange(param);
                            }
                            SqlHelper.Con.Open();
    
                            OracleDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
    
                            while (reader.Read())
                            {
                                T obj = SqlHelper.ExecuteDataReader<T>(reader);
                                list.Add(obj);
                            }
                        }
                        catch (Exception ex)
                        {
                            list = null;
                        }
                    }
                }
                finally
                {
                    if (SqlHelper.Con.State != ConnectionState.Closed)
                    {
                        SqlHelper.Con.Close();
                    }
                }
                return list;
            }
    
            #endregion
        }
    }
    create table FILEIMAGE
    (
      name        VARCHAR2(60),
      filename    VARCHAR2(60),
      filedesc    VARCHAR2(200),
      guid        VARCHAR2(50) not null,
      fileextname VARCHAR2(10),
      savepath    VARCHAR2(100),
      createddate DATE
    )

    web 实现思路,其他不用更改,只需要在传参哪里改为web实现获取这4个(文件名,扩展名,文件大小,文件转成byte[])数据传到后台即可

  • 相关阅读:
    mysql 获取blob类型的值
    idea导入 spring framework源码
    SpringBoot集成Swagger2,3分钟轻松入手!
    mysql索引类型:FULLTEXT、NORMAL、SPATIAL、UNIQUE的区别
    Spring Boot 如何解决项目启动时初始化资源
    微服务架构设计基础之领域驱动设计
    Spring Boot 集成 Memcached
    zookeeper简单实现注册与发现以及其他基本操作
    什么是RPC,RPC好处,常用的RPC框架
    Thrift IDL基本语法
  • 原文地址:https://www.cnblogs.com/macT/p/9964299.html
Copyright © 2020-2023  润新知