我在Angular上有一个简单的表单,我在其中上传文件和描述。
constructor(private http: HttpClient) { }
upload(files) {
if (files.length === 0)
return;
const formData: FormData = new FormData();
var filedesc = this.description;
for (let file of files) {
formData.append(file.name, file);
formData.append("Description", filedesc);
}
const uploadReq = new HttpRequest('POST', `api/upload`, formData, {
reportProgress: true,
});
在控制器中,我仅获得文件名。
[HttpPost, DisableRequestSizeLimit]
public ActionResult UploadFile()
{
try
{
var fileContent = Request.Form.Files[0];
string folderName = "Upload";
var contenttype = "application/vnd.openxmlformats-officedocument.presentationml.presentation";
string webRootPath = _hostingEnvironment.WebRootPath;
string newPath = Path.Combine(webRootPath, folderName);
if (!Directory.Exists(newPath))
{
Directory.CreateDirectory(newPath);
}
if (fileContent.Length > 0)
{
if (fileContent.ContentType == contenttype)
{
string fileName = ContentDispositionHeaderValue.Parse(fileContent.ContentDisposition).FileName.Trim('"');
string fullPath = Path.Combine(newPath, fileName);
using (var stream = new FileStream(fullPath, FileMode.Create))
{
fileContent.CopyTo(stream);
}
}
else
{
return Json("Wrong File Type.");
}
我的问题是在这种情况下如何接收描述字符串?还是在一个请求中附加文件和描述是不好的吗?
答案 0 :(得分:1)
您必须在操作方法中添加一个参数才能接收描述:
builder.Services.AddScoped<IContractService1, ContractService1>();
builder.Services.AddScoped<IContractService2, ContractService2>();
可以在同一请求中发送带有文件的表格数据。这就是//If you are expecting a single file description
public ActionResult UploadFile(string description)
{
//Logic..
}
//If you are expecting multiple file descriptions
public ActionResult UploadFile(IEnumerable<string> description)
{
//Logic..
}
内容类型标头的用途。
答案 1 :(得分:1)
就像之前说过的Aman B一样,添加一个参数并使用此代码
setState