На угловом сайте используйте этот код
file: any;
onSelectFile($event, file) {
this.file = file;
}
uploadImage() {
if (this.file.length === 0) {
return;
}
const formData = new FormData();
for (let file of this.file)
formData.append(file.name, file);
const uploadReq = new HttpRequest('POST', `api/FileUpload`, formData, {
reportProgress: true,
});
this.http.request(uploadReq).subscribe(event => {
if (event.type === HttpEventType.UploadProgress) {
this.progress = Math.round(100 * event.loaded / event.total);
}
});
}
здесь onSelectFile
должен вызываться при вводе, как этот
<input #file type='file' multiple (change)="onSelectFile($event, file.files)">
А на вашем сайте asp.net используйте этот код
[Produces("application/json")]
[Route("api/[controller]")]
public class FileUploadController : Controller
{
private IHostingEnvironment _hostingEnvironment;
public FileUploadController(IHostingEnvironment hostingEnvironment)
{
_hostingEnvironment = hostingEnvironment;
}
[HttpPost, DisableRequestSizeLimit]
public ObjectResult UploadFile()
{
try
{
var file = Request.Form.Files[0];
string folderName = "Upload";
string webRootPath = _hostingEnvironment.WebRootPath;
string newPath = Path.Combine(webRootPath, folderName);
if (!Directory.Exists(newPath))
{
Directory.CreateDirectory(newPath);
}
string fileName = "";
if (file.Length > 0)
{
fileName = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"');
string fullPath = Path.Combine(newPath, fileName);
using (var stream = new FileStream(fullPath, FileMode.Create))
{
file.CopyTo(stream);
}
}
return Ok(fileName);
}
catch (System.Exception ex)
{
return BadRequest(ex.Message);
}
}
}
Спасибо