可以使用ASP.NET WEB API上传图片,但在部署时不能上传图片

时间:2019-10-26 22:32:00

标签: asp.net-web-api postman

我正在使用ASP.NET WEB API将图像上传到服务器。但是,当我将我的Web API的源代码上传到gearhost.com并发出发布请求时。我无法发布图片。这是我的Web API控制器代码:

[Route("upload")]
[HttpPost]
public async Task<string> Upload()
{
    var ctx = HttpContext.Current;
    var root = ctx.Server.MapPath("/uploads/");
    var provider = new MultipartFormDataStreamProvider(root);

    try
    {
        await Request.Content
                .ReadAsMultipartAsync(provider);

        foreach (var file in provider.FileData)
        {
            var name = file.Headers
                           .ContentDisposition
                           .FileName;

            // remove double quotes from string.
            name = name.Trim('"');

            var localFileName = file.LocalFileName;
            var filePath = Path.Combine(root, "files", name);

            // File.Move(localFileName, filePath);
            // SaveFilePathSQLServerADO(localFileName, filePath);
            // SaveFileBinarySQLServerADO(localFileName, name);

            // SaveFilePathSQLServerEF(localFileName, filePath);
            SaveFileBinarySQLServerEF(localFileName, name, filePath);

            if (File.Exists(localFileName))
                File.Delete(localFileName);
        }
    }
    catch 
    {
        return "Error";
    }

    return "File uploaded successfully!";
}

public void SaveFileBinarySQLServerEF(string localFile, string fileName, string filePath)
{
    // 1) Get file binary
    byte[] fileBytes;

    using (var fs = new FileStream(localFile, FileMode.Open, FileAccess.Read))
    {
        fileBytes = new byte[fs.Length];
        fs.Read(fileBytes, 0, Convert.ToInt32(fs.Length));
    }

    // 2) Create a Files object
    var file = new tblimage()
                   {
                       Data = fileBytes,
                       Names = fileName,
                       ContentType = filePath
                   };

    // 3) Add and save it in database
    using (var ctx = new coachEntities())
    {
        ctx.tblimages.Add(file);

        ctx.SaveChanges();
    }
}

这是来自本地主机的成功呼叫:

Image posted through localhost

但是,当部署相同的代码并通过邮递员发出请求时,我会收到此错误:

Image posted through live server

2 个答案:

答案 0 :(得分:0)

也许,“上传”没有写权限 检查您的上载文件夹中的权限。 转到属性-安全 授予读写权限。

答案 1 :(得分:0)

尽管在实时代码中返回异常详细信息不是一个好主意。由于您不维护日志。为了进行测试,请返回异常详细信息。另外,由于代码中没有响应,您如何获得“无法上传,请重试”之类的响应