You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

AngularJS对接Web API:文件二进制存数据库的C#上传下载方案咨询

Got it, let's walk through how to implement binary file uploads and downloads between your AngularJS portal, C# Web API, and database using your existing stored procedures. We'll cover both the API layer and the AngularJS frontend hooks in detail.

C# Web API Implementation for Binary File Management

File Upload (POST to Database)

Core Approach

  1. Receive file data from AngularJS: We'll use FormData to wrap both file metadata (filename, MIME type) and binary content—it's browser-friendly and easy to parse in the API.
  2. Parse the request in Web API, extract the file's byte array and metadata.
  3. Call your InsertDocuments stored procedure, passing in all required parameters (filename, MIME type, binary content, etc.).
  4. Return a success response (like the new document ID) to the frontend for confirmation.

C# Web API Controller Code

using System.Data;
using System.Data.SqlClient;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http;

public class DocumentsController : ApiController
{
    // Replace with your actual database connection string
    private readonly string _connectionString = "YourDatabaseConnectionString";

    [HttpPost]
    [Route("api/documents/upload")]
    public async Task<IHttpActionResult> UploadFile()
    {
        if (!Request.Content.IsMimeMultipartContent())
        {
            return BadRequest("Unsupported media type. Please use multipart/form-data.");
        }

        // Temporary storage for uploaded file stream
        var streamProvider = new MultipartFormDataStreamProvider(System.IO.Path.GetTempPath());
        await Request.Content.ReadAsMultipartAsync(streamProvider);

        // Extract file and metadata from form data
        var uploadedFile = streamProvider.FileData[0];
        var fileName = streamProvider.FormData["fileName"];
        var mimeType = streamProvider.FormData["mimeType"];

        // Convert file to byte array
        byte[] fileBytes = await System.IO.File.ReadAllBytesAsync(uploadedFile.LocalFileName);

        // Execute stored procedure to insert into database
        using (var conn = new SqlConnection(_connectionString))
        {
            await conn.OpenAsync();
            using (var cmd = new SqlCommand("InsertDocuments", conn))
            {
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.AddWithValue("@FileName", fileName);
                cmd.Parameters.AddWithValue("@MimeType", mimeType);
                cmd.Parameters.AddWithValue("@FileContent", fileBytes);

                // Capture the output DocumentId if your stored procedure returns it
                var docIdParam = new SqlParameter("@DocumentId", SqlDbType.Int)
                {
                    Direction = ParameterDirection.Output
                };
                cmd.Parameters.Add(docIdParam);

                await cmd.ExecuteNonQueryAsync();
                int newDocId = (int)docIdParam.Value;

                return Ok(new { DocumentId = newDocId, Message = "File uploaded successfully" });
            }
        }
    }
}

AngularJS Upload Service & Controller Code

// Service to handle upload logic
app.service('documentService', ['$http', function($http) {
    this.uploadFile = function(selectedFile) {
        const formData = new FormData();
        formData.append('file', selectedFile);
        formData.append('fileName', selectedFile.name);
        formData.append('mimeType', selectedFile.type);

        return $http.post('/api/documents/upload', formData, {
            transformRequest: angular.identity,
            headers: { 'Content-Type': undefined }
        });
    };
}]);

// Controller to handle user input
app.controller('UploadController', ['documentService', function(documentService) {
    this.handleFileSelect = function(event) {
        const file = event.target.files[0];
        documentService.uploadFile(file)
            .then(response => {
                console.log('Upload successful:', response.data);
                // Add your success logic here (e.g., show notification, refresh document list)
            })
            .catch(error => {
                console.error('Upload failed:', error);
                // Add error handling here (e.g., show error message)
            });
    };
}]);

File Download (Retrieve Binary from Database)

Core Approach

  1. Accept a document ID parameter from the frontend.
  2. Call your GetDocument stored procedure to fetch the file's byte array, filename, and MIME type.
  3. Set HTTP response headers to tell the browser to treat the response as a downloadable file.
  4. Return the binary data as a file stream.

C# Web API Controller Code

[HttpGet]
[Route("api/documents/download/{docId}")]
public async Task<IHttpActionResult> DownloadFile(int docId)
{
    byte[] fileBytes = null;
    string fileName = null;
    string mimeType = null;

    using (var conn = new SqlConnection(_connectionString))
    {
        await conn.OpenAsync();
        using (var cmd = new SqlCommand("GetDocument", conn))
        {
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.AddWithValue("@DocumentId", docId);

            using (var reader = await cmd.ExecuteReaderAsync())
            {
                if (reader.Read())
                {
                    fileBytes = (byte[])reader["FileContent"];
                    fileName = reader["FileName"].ToString();
                    mimeType = reader["MimeType"].ToString();
                }
                else
                {
                    return NotFound(); // Return 404 if document doesn't exist
                }
            }
        }
    }

    // Configure response headers to trigger download
    var response = new HttpResponseMessage(HttpStatusCode.OK)
    {
        Content = new ByteArrayContent(fileBytes)
    };
    response.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue(mimeType);
    response.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment")
    {
        FileName = fileName
    };

    return ResponseMessage(response);
}

AngularJS Download Function

// Update the document service to include download logic
app.service('documentService', ['$http', function($http) {
    // ... existing upload code ...

    this.downloadFile = function(docId) {
        // Use window.open to trigger the browser's download dialog
        window.open(`/api/documents/download/${docId}`, '_blank');
    };
}]);

// Controller usage for document list
app.controller('DocumentListController', ['documentService', function(documentService) {
    this.initiateDownload = function(docId) {
        documentService.downloadFile(docId);
    };
}]);

Additional Best Practices

  • Error Handling: Wrap database calls in try-catch blocks to handle exceptions, and return appropriate HTTP status codes (e.g., 500 for server errors).
  • File Size Limits: Adjust your Web API's web.config to allow larger uploads by modifying maxRequestLength (for IIS) and maxAllowedContentLength (for ASP.NET).
  • Document Listing: Add an API endpoint to call your GetDocuments stored procedure, returning a list of document metadata (IDs, filenames, upload dates) for your AngularJS portal to display.
  • Security: Validate file types and sizes on both frontend and backend to prevent malicious uploads.

内容的提问来源于stack exchange,提问作者user3376642

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 08:17:41