不要將文件保存到SQL服務器 - 這不是它的用途。看到這個答案: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";
}
謝謝你的回覆。我試過你寫的代碼,但我得到一個服務器錯誤415(不支持的媒體類型)。它甚至不會去我的web api控制器。有什麼我可能會失蹤?再次謝謝你。 – vbravo
這是一個服務器錯誤;與Javascript無關。確保API控制器接受您正在上傳的文件。 – Kyle