首页 > 解决方案 > 如何在 C# 中转换 pdf 或 jpg 中的字节

问题描述

我有一个 base64 代码以及文件的名称和扩展名,我使用以下代码将其转换为字节

byte[] sPDFDecoded = Convert.FromBase64String(request.SetMcfile);

Code64="JVBERi0xLjcNCiWhs8XXDQoxIDAgb2JqDQo8PC9QYWdlcyAyIDAgUiAvVHlwZS9DYXRhbG9nPj4NCmVuZG9iag0KMiAwIG9iag0KPDwvQ291bnQgMTUvS2lkc1sgNCAwIFIgIDIzIDAgUiAgNTEgMCBSICA1NyAwIFIgIDY0IDAgUiAgNzAgMCBSICA3NyAwIFIgIDgzIDAgUiAgOTAgMCBSICA5NiAwIFIgIDEwMyAwIFIgIDEwOSAwIFIgIDEy"

FileName = "Resumen.pdf"

我想转换为具有相同名称和相同扩展名的真实文件,以将其发送到 ftp 服务器。

我将文件保存到 ftp 的方法如下:

public async Task<bool> UploadFile(IFormFile file)
{
    long MaxSize = 10;

    var extension = Path.GetExtension(file.FileName);
    var allowedExtensions = new[] { ".jpg", ".pdf", ".jpeg" };

    if (!allowedExtensions[0].Equals(extension) && !allowedExtensions[1].Equals(extension) && !allowedExtensions[2].Equals(extension))
    {
        throw new ManejadorException(HttpStatusCode.BadRequest, "Los tipos de archivos permitidos son [.jpg, pdf]");
    }

    long fileSizeInBytes = file.Length;

    // Convert the bytes to Kilobytes (1 KB = 1024 Bytes)
    long fileSizeInKB = fileSizeInBytes / 1024;

    // Convert the KB to MegaBytes (1 MB = 1024 KBytes)
    long fileSizeInMB = fileSizeInKB / 1024;

    if (fileSizeInMB > MaxSize)
    {
        throw new ManejadorException(HttpStatusCode.BadRequest, "El archivo supero el peso permitido 10MB");
    }

    // Create an FtpWebRequest
    var request = (FtpWebRequest)WebRequest.Create("ftp://tiendashipi.com/" + file.FileName);

    // Set the method to UploadFile
    request.Method = WebRequestMethods.Ftp.UploadFile;

    // Set the NetworkCredentials
    request.Credentials = new NetworkCredential("xxxx", "xxxx");

    // Set buffer length to any value you find appropriate for your use case
    byte[] buffer = new byte[1024];
    var stream = file.OpenReadStream();
    byte[] fileContents;

    // Copy everything to the 'fileContents' byte array
    using (var ms = new MemoryStream())
    {
        int read;

        while ((read = stream.Read(buffer, 0, buffer.Length)) > 0)
        {
            ms.Write(buffer, 0, read);
        }

        fileContents = ms.ToArray();
    }

    // Upload the 'fileContents' byte array 
    using (Stream requestStream = request.GetRequestStream())
    {
        await requestStream.WriteAsync(fileContents, 0, fileContents.Length);
    }

    // Get the response
    // Some proper handling is needed
    var response = (FtpWebResponse)request.GetResponse();

    return response.StatusCode == FtpStatusCode.FileActionOK;
}

标签: c#.net-corebase64

解决方案


推荐阅读