I have a base64 code and the name and extension of the file I convert it into byte using the following code
byte[] sPDFDecoded = Convert.FromBase64String(request.SetMcfile);
Code64="JVBERi0xLjcNCiWhs8XXDQoxIDAgb2JqDQo8PC9QYWdlcyAyIDAgUiAvVHlwZS9DYXRhbG9nPj4NCmVuZG9iag0KMiAwIG9iag0KPDwvQ291bnQgMTUvS2lkc1sgNCAwIFIgIDIzIDAgUiAgNTEgMCBSICA1NyAwIFIgIDY0IDAgUiAgNzAgMCBSICA3NyAwIFIgIDgzIDAgUiAgOTAgMCBSICA5NiAwIFIgIDEwMyAwIFIgIDEwOSAwIFIgIDEy"
FileName = "Resumen.pdf"
I want to convert to the real file with the same name and the same extension to send it to an ftp server.
My method to save the file to ftp is as follows:
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;
}