>  기사  >  백엔드 개발  >  C# 파일 업로드 및 다운로드(바이너리 스트림으로 데이터베이스에 저장)

C# 파일 업로드 및 다운로드(바이너리 스트림으로 데이터베이스에 저장)

大家讲道理
大家讲道理원래의
2016-11-10 14:54:102344검색

1. 파일을 바이너리 스트림 형식으로 데이터베이스에 씁니다.

먼저 파일 경로를 구한 다음 파일을 바이너리로 읽어서 바이너리 배열로 저장하고 데이터베이스와 연결을 설정한 후 다음을 입력합니다. 해당 매개변수에 바이너리 배열을 할당하여 파일을 데이터베이스에 쓰는 작업을 완료합니다

/// 将文件流写入数据库  
/// </summary>  
/// <param name="filePath">存入数据库文件的路径</param>  
/// <param name="id">数据库中插入文件的行标示符ID</param>  
/// <returns></returns>  
public int UploadFile(string filePath, string id)  
{  
    byte[] buffer = null;  
    int result = 0;  
    if (!string.IsNullOrEmpty(filePath))  
    {  
        String file = HttpContext.Current.Server.MapPath(filePath);   
        buffer = File.ReadAllBytes(file);  
        using (SqlConnection conn = new SqlConnection(DBOperator.ConnString))  
        {  
            using (SqlCommand cmd = conn.CreateCommand())  
            {  
                cmd.CommandText = "update DomesticCompanyManage_Main_T set ZBDocumentFile = @fileContents where MainID =&#39;" + id + "&#39;";;  
                cmd.Parameters.AddRange(new[]{  
                new SqlParameter("@fileContents",buffer)  
            });  
                conn.Open();  
                result = cmd.ExecuteNonQuery();  
                conn.Close();  
            }  
        }  
        return result;  
    }  
    else 
        return 0;  
}

2. 데이터베이스에서 파일을 읽고 해당 형식의 파일을 생성합니다

데이터베이스에서 파일을 읽으려면 필요한 경로에 따라 해당 파일을 생성한 다음 데이터베이스에 저장된 바이너리 스트림을 새 파일에 씁니다.

같은 이름의 파일이 있는 경우. 디렉터리, 원본 파일을 덮어씁니다

//从数据库中读取文件流  
//shipmain.Rows[0]["ZBDocument"],文件的完整路径  
//shipmain.Rows[0]["ZBDocumentFile"],数据库中存放的文件流  
if (shipmain.Rows[0]["ZBDocumentFile"] != DBNull.Value)  
{  
    int arraySize = ((byte[])shipmain.Rows[0]["ZBDocumentFile"]).GetUpperBound(0);  
    FileStream fs = new FileStream(HttpContext.Current.Server.MapPath(shipmain.Rows[0]["ZBDocument"].ToString()), FileMode.OpenOrCreate, FileAccess.Write);//由数据库中的数据形成文件  
    fs.Write((byte[])shipmain.Rows[0]["ZBDocumentFile"], 0, arraySize);  
    fs.Close();  
}


성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.