I am uploading multiple files through a form and then iterating through each file and am creating a zero byte temp file and getting the file name using the GetTempFileName. Is there a way to copy the file itself not just the file name and the zero byte?. The code runs but i always get the zero byte file on the other end of my API which should happen. My code is like below.
public async Task<IActionResult> UploadDocumentsAsync(Documents files)
{
try
{
List<string> tempFilePath = new List<string>();
List<string> fileName = new List<string>();
foreach (var doc in files.documents)
{
tempFilePath.Add(Path.GetTempFileName());
fileName.Add(doc.FileName);
}
MultipartFormDataContent formData = new MultipartFormDataContent();
var filePath = tempFilePath;
string token = Token();
List<FileStream> streams = new List<FileStream>();
using (var client = new HttpClient())
{
using (var content = new MultipartFormDataContent())
{
for (int i = 0; i < tempFilePath.Count; i )
{
var fileStream = new FileStream(tempFilePath[i], FileMode.Open);
formData.Add(new StreamContent(fileStream), fileName[i], fileName[i]);
streams.Add(fileStream);
}
var request = new HttpRequestMessage(HttpMethod.Post, new Uri(_configuration["Application:AppDomain"]) "api/Document")
{
Content = formData
};
request.Headers.Add("accept", "application/json");
var response = await client.SendAsync(request);
streams.ForEach(stream =>
{
stream.Dispose();
});
if (response.IsSuccessStatusCode)
{
//Handle success
}
//Handle failure
}
}
}
catch (Exception e)
{
//Handle the exception
}
}
CodePudding user response:
You need to save the actual file to temp fileName if you want to access it later
public async Task<IActionResult> UploadDocumentsAsync(Documents files)
{
try
{
List<string> tempFilePath = new List<string>();
List<string> fileName = new List<string>();
foreach (var doc in files.documents)
{
string fileTempFileName = Path.GetTempFileName();
tempFilePath.Add(fileTempFileName );
fileName.Add(doc.FileName);
using(Stream outStream = File.OpenWrite(Path.Combine(Path.GetTempPath(), fileTempFilePath )))
{
doc.CopyTo(outStream);
}
}
//Continue your code [...]
}
catch (Exception e)
{
//Handle the exception
}
}