嗨,在我的asp.net核心项目中有文件上传控制器。我想将文件更改为唯一名称(例如:当前数据+时间+唯一ID),然后返回该名称以用于前端Angular应用程序。
Angular 7 CLI ASP.net Core v2.2
[Route("CustomerFileUpload")]
[HttpPost, DisableRequestSizeLimit]
public IActionResult Upload()
{
try
{
var file = Request.Form.Files[0];
var folderName = Path.Combine("Upload_files", "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);
}
return Ok(new { dbPath });
}
else
{
return BadRequest();
}
}
catch (Exception)
{
return StatusCode(500, "Internal server error");
}
}
app.UseStaticFiles();
app.UseStaticFiles(new StaticFileOptions()
{
FileProvider = new
PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), @"Upload_files")),
RequestPath = new PathString("/Upload_files")
});
public uploadFile (files){
if (files.length === 0) {
return;
}
let fileToUpload = <File>files[0];
const ImageData = new FormData();
ImageData.append('file', fileToUpload, fileToUpload.name);
this.http.post('https://localhost:44301/api/Customer/CustomerFileUpload', ImageData)
.subscribe(response => {
console.log("image upload ----> "+response)
});
}
<input type="file" #file placeholder="Choose file" >
<button type="button" class="btn btn-primary" (click)="uploadFile(file.files)"> Upload </button>
答案 0 :(得分:0)
您可以使用
return Ok(dbPath);
因此,您无需在此处使用新关键字
new { dbPath }
然后在您的角度应用程序中添加如下内容
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json'
}),
observe: 'response'
};
this.http.post('https://localhost:44301/api/Customer/CustomerFileUpload', ImageData, httpOptions)
.subscribe(response => {
console.log("image upload ----> "+response)
});