我正在寻找一种解决方案,可以将任何文件从AngularJS前端上传到.Net Web 2,并直接上传到server数据库。我做了一些研究,对于angularjs,我主要看的是ng文件上传。我的问题是,我所看到的大多数解决方案都将文件保存到临时文件夹中。我不确定这是否可能,但我希望它直接放到一个SQL server表中。
我已经看到了一些解决方案,它将文件转换为字节数组,可以保存到SQL表中,但我不知道如何在.NET web 2和angularjs前端实现这一点。提前谢谢你。
发布于 2016-04-25 18:31:18
不要将文件保存到SQL server--这不是它的目的。看这个答案:In MVC4, how do I upload a file (an image) to SQL Server that's part of my domain model?和这个答案:Storing files in SQL Server
上传文件的角度是容易的。这样做吧:
控制器
$scope.uploadFile = function() {
//get the filename from the <input type='file'>
//angular doesn't allow attaching ngModel to file input
var fileInput = document.getElementById("myInputId");
//check if there's a file
if(fileInput.files.length === 0) return;
//you cannot send a file as JSON because json is in the string format
//for fileuploads, you must send as a FormData() object
//C# accepts HttpPostedFileBase as the file argument
var file = fileInput.files[0];
//put the file in a new formdata object
var payload = new FormData();
payload.append("file", file);
//upload file to C# controller
$http.post("path/to/C#/controller", payload, {
//you **need** to specify these options, without them upload does not work
transformRequest: angular.identity,
headers: { "Content-Type": undefined }
}).then(function(data) {
//success
}, function(error) {
//error
});
}C#/ASP.NET
[WebMethod]
public string UploadFile(HttpPostedFileBase file) {
//access the file object here
var inputStream = file.InputStream;
var fileName = Path.GetFileName(file.FileName);
try
{
file.SaveAs("local/path" + fileName);
}
catch (IOException exc)
{
return "Error: " + exc.Message;
}
return "success";
}https://stackoverflow.com/questions/36847133
复制相似问题