从post发布webAPI中的输入值

时间:2018-06-12 14:57:05

标签: c# post asp.net-web-api

我使用以下代码使用webAPI上传文件,文件上传部分工作正常,但如何从帖子中访问所有其他输入值和隐藏的输入值?

        [HttpPost]
    public async Task<object> UploadFile()
    {
        if (!Request.Content.IsMimeMultipartContent("form-data"))
        {
            throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.UnsupportedMediaType));
        }

        var streamProvider = new MultipartFormDataStreamProvider(HttpContext.Current.Server.MapPath("~/App_Data/Temp/"));

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


            foreach (MultipartFileData fileData in streamProvider.FileData)
            {
                var fileName = "";
                if (string.IsNullOrEmpty(fileData.Headers.ContentDisposition.FileName))
                {
                    fileName = Guid.NewGuid().ToString();
                }
                fileName = fileData.Headers.ContentDisposition.FileName;
                if (fileName.StartsWith("\"") && fileName.EndsWith("\""))
                {
                    fileName = fileName.Trim('"');
                }
                if (fileName.Contains(@"/") || fileName.Contains(@"\"))
                {
                    fileName = Path.GetFileName(fileName);
                }
                File.Move(fileData.LocalFileName, Path.Combine(HttpContext.Current.Server.MapPath("~/App_Data/"), Path.GetDirectoryName(fileName) + Guid.NewGuid() + Path.GetExtension(fileName)));

            }
            return Request.CreateResponse(HttpStatusCode.OK);
        }
        catch (Exception e)
        {
            return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e);
        }
    }

以下是我用于发布文件的表单。

<form name="form1" method="post" enctype="multipart/form-data" action="api/upload">
<div>
    <label for="caption">Image Caption</label>
    <input name="caption" type="text" />
</div>
<div>
    <input type="hidden" value="secretvalue"/>
    <label for="image1">Image File</label>
    <input name="image1" type="file" />
</div>
<div>
    <input type="submit" value="Submit" />
</div>

0 个答案:

没有答案