[英]How to upload a file in angular
我是 Angular CLI 的新手,我想创建一个文件上传器。 就我而言,我需要将文件存储在应用程序的文件夹中,而不是在它之外。 我查看了 web,但找不到任何信息。 准确地说,我想将它们存储在资产文件夹assets/media
中
我怎么做?
我有这样的东西: html
<div class="col-md-12">
<input type="file" accept=".pdf, .txt" #file placeholder="Choose file" (change)="uploadFile(file.files)" style="display:none;">
<button style="width: 350px" type="button" class="btn btn-success" (click)="file.click()">Dodaj plik</button>
js
public uploadFile = (files) => {
if (files.length === 0) {
return;
}
let fileToUpload = <File>files[0];
const formData = new FormData();
formData.append('file', fileToUpload, fileToUpload.name);
this._http.post(this.baseURL + "item/addFile/", formData, { reportProgress: true, observe: 'events' })
.subscribe(event => {
c#
[HttpPost, DisableRequestSizeLimit]
[Route("/item/addFile")]
public IActionResult Upload()
{
try
{
var file = Request.Form.Files[0];
var folderName = Path.Combine("Resources", "Images");
var pathToSave = Path.Combine(Directory.GetCurrentDirectory(), folderName);
if (file.Length > 0)
{
var fileName = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"');
var fullPath = Path.Combine(pathToSave, fileName);
var dbPath = Path.Combine(folderName, fileName);
using (var stream = new FileStream(fullPath, FileMode.Create))
{
file.CopyTo(stream);
}
//save to db
return Ok(new { dbPath });
}
else
{
return BadRequest();
}
}
catch (Exception ex)
{
return StatusCode(500, $"Internal server error: {ex}");
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.