我正在编辑此帖子,以便在下方显示我的最新尝试。 我一直在寻找试图寻找解决方案的论坛。我有一个ASP.NET MVC应用程序,我在其中使用Angular。我正在尝试使用danialfarid / ng-file-upload来允许用户上传PDF,然后将其作为二进制数据保存到数据库中(不是我的想法,但我必须这样做)。
我的HTML中有以下内容(摘自示例):
File:<input type="file" ngf-select ng-model="picFile" name="file" accept="image/*" ngf-max-size="2MB" required ngf-model-invalid="errorFile"><br />
<img ngf-thumbnail="picFile" class="thumb"> <button ng-click="picFile = null" ng-show="picFile">Remove</button><br />
<button type="button" class="btn btn-primary" ng-click="uploadPic(picFile)">Upload</button>
这在我的Angular控制器中:
$scope.uploadPic = function (files) {
file.upload = Upload.upload({
url: '/SSQV4/SSQV5/Document/UploadEMRDocument',
data: {file: files}
})
}
我的MVC控制器:
namespace SSQV5.Controllers
{
public class DocumentController : ApiController
{
public async Task<IHttpActionResult> UploadEMRDocument()
{
try
{
var provider = new MultipartMemoryStreamProvider();
await Request.Content.ReadAsMultipartAsync(provider);
var f = provider.Contents.First(); // assumes that the file is the only data
if (f != null)
{
var filename = f.Headers.ContentDisposition.FileName.Trim('\"');
filename = Path.GetFileName(filename);
var buffer = await f.ReadAsByteArrayAsync();
//buffer now contains the file content,
//and filename has the original filename that was uploaded
//do some processing with it (e.g. save to database)
}
else
{
return BadRequest("Attachment failed to upload");
}
}
catch (Exception ex)
{
return BadRequest(ex.Message);
}
return Ok();
}
}
}
此代码根本不会访问MVC控制器。我显然遗漏了一些东西,但我对这可能是什么没有丝毫的线索。非常感谢任何帮助!
答案 0 :(得分:1)
配置上传时,指定将文件发布到的URL:
file.upload = Upload.upload({
url: 'myMVC/MyMethod',
data: {file: file}
})
答案 1 :(得分:1)
您需要从表单数据中提取文件内容。
以下是我如何执行此操作(使用ng-file-upload
以与前端相同的方式)在我的应用程序中上传附件。
public async Task<IHttpActionResult> UploadAttachment()
{
// Check if the request contains multipart/form-data.
try
{
var provider = new MultipartMemoryStreamProvider();
await Request.Content.ReadAsMultipartAsync(provider);
var f = provider.Contents.First(); // assumes that the file is the only data
if (f != null)
{
var filename = f.Headers.ContentDisposition.FileName.Trim('\"');
filename = Path.GetFileName(filename);
var buffer = await f.ReadAsByteArrayAsync();
//buffer now contains the file content,
//and filename has the original filename that was uploaded
//do some processing with it (e.g. save to database)
}
else
{
return BadRequest("Attachment failed to upload");
}
}
catch (Exception ex)
{
return BadRequest(ex.Message);
}
return Ok();
}