Я использую загрузку файла AngularJS (https://github.com/nervgh/angular-file-upload), и он не работает последовательно для одного и того же файла снова и снова. Не уверен, что это в коде AngularJS или моем коде REST API.
Мой код контроллера -
[Route("uploadFile")]
[HttpPost]
public void UploadFile()
{
var httpPostedFile = HttpContext.Current.Request.Files["file"];
var folderExists = Directory.Exists(HttpContext.Current.Server.MapPath("~/UploadedDocuments"));
if (!folderExists)
Directory.CreateDirectory(HttpContext.Current.Server.MapPath("~/UploadedDocuments"));
if (httpPostedFile != null)
{
var fileSavePath = Path.Combine(HttpContext.Current.Server.MapPath("~/UploadedDocuments"), httpPostedFile.FileName);
httpPostedFile.SaveAs(fileSavePath);
}
}
Мой контроллер AngularJS -
var uploader = $scope.uploader = new FileUploader({
url: apiUrl.serviceBase + "api/quotes/uploadFile"
});
uploader.onSuccessItem = function (fileItem) {
$scope.uploader.queue = [];
$scope.uploader.progress = 0;
alert("Selected file has been uploaded successfully.");
vm.file.fileName = fileItem.file.name;
vm.file.originatedBy = vm.userName;
vm.file.modifiedBy = vm.userName;
vm.file.rfq = vm.rfq;
quotesService.updateFile(vm.file).then(processSuccess, processError);
$location.path("/quotes");
};
uploader.onErrorItem = function () {
alert("We were unable to upload your file. Please try again.");
};
Мой HTML-код -
<tbody>
<tr ng-repeat="item in uploader.queue">
<td><strong>{{ item.file.name }}</strong></td>
<td ng-show="uploader.isHTML5" nowrap>{{ item.file.size/1024/1024|number:2 }} MB</td>
<td ng-show="uploader.isHTML5">
<div class="progress" style="margin-bottom: 0;">
<div class="progress-bar" role="progressbar" ng-style="{ 'width': item.progress + '%' }"></div>
</div>
</td>
<td class="text-center">
<span ng-show="item.isSuccess"><i class="glyphicon glyphicon-ok"></i></span>
<span ng-show="item.isCancel"><i class="glyphicon glyphicon-ban-circle"></i></span>
<span ng-show="item.isError"><i class="glyphicon glyphicon-remove"></i></span>
</td>
<td nowrap>
<button type="button" class="btn btn-success btn-xs" ng-click="item.upload()" ng-disabled="item.isReady || item.isUploading || item.isSuccess">
<span class="glyphicon glyphicon-upload"></span> Upload
</button>
<button type="button" class="btn btn-warning btn-xs" ng-click="item.cancel()" ng-disabled="!item.isUploading">
<span class="glyphicon glyphicon-ban-circle"></span> Cancel
</button>
<button type="button" class="btn btn-danger btn-xs" ng-click="item.remove()">
<span class="glyphicon glyphicon-trash"></span> Remove
</button>
</td>
</tr>
</tbody>
</table>
Я не уверен, где ошибка, иногда она никогда не попадает в REST API. То, как я тестирую, пытается загружать один и тот же файл снова и снова. Должен ли я что-то делать после вызова функции saveas?
Это предложение слишком длинное для комментариев
Это источник класса HttpPostFile, который находится здесь.
public void SaveAs(String filename) {
// VSWhidbey 82855
if (!Path.IsPathRooted(filename)) {
HttpRuntimeSection config = RuntimeConfig.GetConfig().HttpRuntime;
if (config.RequireRootedSaveAsPath) {
throw new HttpException(SR.GetString(SR.SaveAs_requires_rooted_path, filename));
}
}
FileStream f = new FileStream(filename, FileMode.Create);
try {
_stream.WriteTo(f);
f.Flush();
}
finally {
f.Close();
}
}
FileMode.Create
- создает новый файл. Если файл уже существует, он перезаписывается.
Поэтому в основном попробуйте использовать FileStream самостоятельно, потому что HttpPostFile
странно не имеет исключения catcher/thrower
[Route("uploadFile")]
[HttpPost]
public void UploadFile()
{
try {
var httpPostedFile = HttpContext.Current.Request.Files["file"];
var folderExists = Directory.Exists(HttpContext.Current.Server.MapPath("~/UploadedDocuments"));
if (!folderExists) Directory.CreateDirectory(HttpContext.Current.Server.MapPath("~/UploadedDocuments"));
if (httpPostedFile != null)
{
var fileSavePath = Path.Combine(HttpContext.Current.Server.MapPath("~/UploadedDocuments"), httpPostedFile.FileName);
HttpInputStream _stream = new HttpInputStream();
FileStream f = new FileStream(fileSavePath, FileMode.Create);
_stream.WriteTo(f);
f.Flush();
}
catch(Exception e){
throw e;
}
finally {
f.Close();
}
}
}
Примечание: я нахожусь на mac и не могу проверить этот код выше, поэтому, пожалуйста, будьте в курсе
public void UploadFile()
? ( должен возвращать URL для загруженного файла imo )