У меня есть угловой интерфейс с Dropzone, и загрузка работает нормально.Я также хочу загрузить тот же файл в тот же URI с помощью Powershell, но не могу.
Кажется, у меня та же проблема, что и здесь. Отправка файла в Web Api через PowerShell , ноу него нет решения.
Это мой сценарий PowerShell:
$file = "test.xml";
$fileBytes = [System.IO.File]::ReadAllBytes($file);
#UTF-8 or ISO-8859-1:
$fileEnc = [System.Text.Encoding]::GetEncoding('UTF-8').GetString($fileBytes);
$boundary = "----" + [System.Guid]::NewGuid().ToString("N");
$LF = "`r`n";
$uri = "http://localhost:3921/api/clients/$clientId/files/upload";
$bodyLines = (
"--$boundary",
"Content-Disposition: form-data; name=`"file`"; filename=`"test.xml`"",
"Content-Type: text/xml$LF",
$fileEnc,
"--$boundary--$LF"
)
#ensure we get a response even if an error's returned
$response = try {
(Invoke-WebRequest -Uri $uri -Method Post -ContentType "multipart/form-data; boundary=$boundary" -Body $bodyLines -ErrorAction Stop)
} catch [System.Net.WebException] {
Write-Verbose "An exception in upload file was caught: $($_.Exception.Message)"
$_.Exception.Response
}
echo $response
Мой соответствующий код C #:
// POST: api/clients/{clientId}/files/upload
[Route("upload")]
public async Task<HttpResponseMessage> Upload(int clientId)
{
// Check if the request contains multipart/form-data.
if (!Request.Content.IsMimeMultipartContent())
{
Log.Error("UnsupportedMediaType");
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
}
var provider = new MultipartFormDataStreamProvider(_root);
try
{
// Read the form data.
await Request.Content.ReadAsMultipartAsync(provider);
// Process the files.
_fileService.UploadFiles(provider, clientId);
_clientsService.SetLastUpdate(clientId, GetUserName());
return Request.CreateResponse(HttpStatusCode.OK);
}
catch (Exception e)
{
Log.Error($"Error in uploading the file for clientId: {clientId}: {e.Message}", e);
return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e);
}
}
Сначала я боролся с передачей Request.Content.IsMimeMultipartContent()
, но этосейчас работает.Теперь он терпит неудачу при await Request.Content.ReadAsMultipartAsync(provider);
с
Unexpected end of MIME multipart stream. MIME multipart message is not complete.
Я попытался поймать POST с помощью Fiddler, но не смог заставить его работать.Я мог поймать POST от Angular, и я вижу, что тела одинаковы.Заголовок из Angular:
POST http://localhost:3921/api/clients/346/files/upload/ HTTP/1.1
Host: localhost:3921
Connection: keep-alive
Content-Length: 3851
Origin: http://localhost:3000
Content-Type: multipart/form-data; boundary=----WebKitFormBoundarywtlOzmNcWI5Nie2v
Accept: application/json
Cache-Control: no-cache
X-Requested-With: XMLHttpRequest
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36
Referer: http://localhost:3000/Client/346/files
Accept-Encoding: gzip, deflate, br
Accept-Language: nl-NL,nl;q=0.9,en-US;q=0.8,en;q=0.7
------WebKitFormBoundarywtlOzmNcWI5Nie2v
Content-Disposition: form-data; name="file[0]"; filename="test.xml"
Content-Type: text/xml
Отладка в C # Я вижу заголовок из PowerShell:
{Content-Length: 3840 Content-Type: multipart/form-data; boundary=----0969905cb7604a579b1c1fa7566756ca}
Что мне кажется нормальным, хотя в * 1024 есть некоторая разница*.
Я также пытался использовать Postman для POST-файла, но не смог заставить его работать вообще.
Я не могу найти то, чего не хватает в моем многочастном потоке.
Пожалуйста, совет.