我的目录中有pdf文件,可以成功打开。我实际上正在更改为 byte[] 并将其压缩到内存流中并返回它。
我将所有文件都压缩了,但是当我打开文件时出现错误
“文件无法打开,可能是不支持的类型或文件已损坏”
我正在将 pdf 文件更改为 byte[],
ArrayList PDFbyteList = new ArrayList();
byte[] bytes = System.IO.File.ReadAllBytes(@"C:\Windows\SysWOW64\config\systemprofile\Desktop\" + PdfFile);
PDFbyteList.Add(bytes);
然后我将其更改为使用内存流压缩,
public FileResult DownloadMultiplePDFFiles(List<FileResult> list)
{
int count = list.Count();
byte[] file1;
using (MemoryStream ms = new MemoryStream())
using (var archive = new ZipArchive(ms, ZipArchiveMode.Create, true))
{
for (var i = 0; i < count; i++)
{
file1 = ObjectToByteArray(PDFbyteList[i]);
string name = list[i].FileDownloadName.Split('.')[0];
name = name + ".pdf";
var zipArchiveEntry = archive.CreateEntry(name, CompressionLevel.Fastest);
using (var zipStream = zipArchiveEntry.Open()) zipStream.Write(file1, 0, file1.Length);
file1 = null;
}
//return File(ms.ToArray(), "application/zip", "Reports.zip");
return File(ms.ToArray(), "application/octet-stream", "Reports.zip");
}
}
参数列表包含内容类型、文件名和字节。我只从这里获取文件名和数组列表中的字节。那么参数列表中的内容类型是“application/octet-stream”。
我尝试使用“application/octet-stream”以及“application/zip”有相同的错误。
可能不会有帮助,但我做了一些修改:
public FileResult DownloadMultiplePDFFiles(IEnumerable<FileResult> files)
{
using MemoryStream ms = new MemoryStream();
using var archive = new ZipArchive(ms, ZipArchiveMode.Create, true);
foreach(var file in files)
{
var bytes = File.ReadAllBytes(@"C:\Windows\SysWOW64\config\systemprofile\Desktop\" + file.FileDownloadName);
string name = $"{file.FileDownloadName.Split('.')[0]}.pdf";
var zipArchiveEntry = archive.CreateEntry(name, CompressionLevel.Fastest);
using var zipStream = zipArchiveEntry.Open();
zipStream.Write(file1, 0, file1.Length);
}
//return File(ms.ToArray(), "application/zip", "Reports.zip");
return File(ms.ToArray(), "application/octet-stream", "Reports.zip");
}