2016-04-25 30 views
0

我正在尋找一種解決方案,可以將任何文件上傳到SQL服務器,從AngularJS前端到.Net Web Api 2,直接到SQL Server數據庫。我已經做了一些研究和angularjs我主要看ng文件上傳。我的問題是我看過的大多數解決方案都將文件保存到臨時文件夾中。我不確定是否有可能,但我希望它直接到SQL服務器表。使用AngularJS進行文件上傳 - > .NET Web Api 2 - > SQL服務器

我見過一些解決方案,它將文件轉換成可保存到SQL表的字節數組,但我不知道如何在.NET web api 2和angularjs前端執行此操作。先謝謝你。

回答

0

不要將文件保存到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"; 
} 
+0

謝謝你的回覆。我試過你寫的代碼,但我得到一個服務器錯誤415(不支持的媒體類型)。它甚至不會去我的web api控制器。有什麼我可能會失蹤?再次謝謝你。 – vbravo

+0

這是一個服務器錯誤;與Javascript無關。確保API控制器接受您正在上傳的文件。 – Kyle

相關問題