使用WebAPI和Angular上传图像

时间:2016-11-30 00:30:10

标签: angularjs asp.net-web-api asp.net-web-api2

以下代码用于上传图片。我想知道用于发布数据的Angular代码和用于在服务器上保存图像的Web API代码。

<form novalidate name="f1" ng-submit="SaveFile()">
<div style="color: red">{{Message}}</div>
<table>
 <tr>
  <td>Select File : </td>
  <td>
    <input type="file" name="file" accept="image/*" onchange="angular.element(this).scope().selectFileforUpload(this.files)" required />
    <span class="error" ng-show="(f1.file.$dirty || IsFormSubmitted) && f1.file.$error.required">Image required!</span>
    <span class="error">{{FileInvalidMessage}}</span>
  </td>
</tr>
<tr>
  <td>Description : </td>
  <td>
    <input type="text" name="uFileDescription" ng-model="FileDescription" class="{{(IsFormSubmitted?'ng-dirty' + (f1.uFileDescription.$invalid?' ng-invalid':''):'')}}" autofocus />
  </td>
</tr>
<tr>
  <td></td>
  <td>
    <input type="submit" value="Upload File" />
  </td>
</tr>

我有保存图像文件的操作方法代码。下面的代码保存图像文件。

    [HttpPost]
    public string SaveFiles(string description)
    {
        string Message = "";
        string fileName, actualFileName;
        Message = fileName = actualFileName = string.Empty;
        bool flag = true;
        var allDatawithmsg = new Data();
        if (Request.Files != null)
        {
            var file = Request.Files[0];
            actualFileName = file.FileName;
            fileName = file.FileName;
            int size = file.ContentLength;
            var folderpath = @"C:/Images/MoreInfo/";
            foreach (string fileinfo in Directory.GetFiles(folderpath))
            {
                string FileName = Path.GetFileName(fileinfo);
                if (actualFileName == FileName)
                {
                    flag = false;
                }
            }
            if (flag)
            {
                try
                {
                    file.SaveAs(Path.Combine(folderpath, fileName));
                    byte[] photo = GetPhoto(Path.Combine(folderpath, fileName));
                    context.sp_updateImageData(actualFileName, fileName, description, size, photo);
                    allDatawithmsg.successMessage = "File upload successfully";
                    allDatawithmsg.imageTableData = GetImageInfo();
                }
                catch (Exception)
                {
                    allDatawithmsg.unSuccessMessage = "File upload failed! Please try again";
                }
            }
            else
            {
                allDatawithmsg.unSuccessMessage = "File already exists ! Please try again";
            }

        }
        var setting = new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() };
        return JsonConvert.SerializeObject(allDatawithmsg, Formatting.Indented, setting);
    }

但我需要转换为网络API方法。如何实现这一目标?

0 个答案:

没有答案