如何在asp.net web api中成功上传后获取发布的文件名

时间:2012-11-28 16:06:00

标签: asp.net-mvc asp.net-web-api

我正在使用asp.net mvc web api。我正在尝试通过帖子请求上传图片,例如

<form action="/api/mypictures/12" method="post" enctype="multipart/form-data">
        <label for="somefile">File</label>
        <input name="somefile" type="file" />
        <input type="submit" value="Submit" />
    </form>

我已遵循以下程序,

[HttpPost]
        public HttpResponseMessage AddImage(HttpRequestMessage request, int id)
        {
            try
            {
                if (!request.Content.IsMimeMultipartContent("form-data"))
                {
                    return request.CreateErrorResponse(HttpStatusCode.UnsupportedMediaType, new HttpError() { { "status", "failed" }, { "message", "Invalid file format" } });
                }
                else
                {
                    string PATH = HttpContext.Current.Server.MapPath("~/App_Data/");
                    var streamProvider = new CustomMultipartFormDataStreamProvider(PATH);
                    var task = Request.Content.ReadAsMultipartAsync(streamProvider).ContinueWith(
                        t =>
                        {
                            if (t.IsFaulted || t.IsCanceled)
                                throw new HttpResponseException(HttpStatusCode.InternalServerError);
                        }
                    );
                    Photo photo = new Photo();
                    photo.Id = id;
                    **photo.Image = "Image that uploaded recently";**
                    photo.IsUserAllowed = true;
                    if (barrepository.AddImage(photo) == 1)
                    {
                        return request.CreateErrorResponse(HttpStatusCode.OK, new HttpError() { { "status", "success" }, { "message", "file uploaded successfully" } });
                    }
                    else
                    {
                        return request.CreateErrorResponse(HttpStatusCode.OK, new HttpError() { { "status", "success" }, { "message", "unable to store the image into database" } });
                    }
                }
            }
            catch(Exception ex)
            {
                return request.CreateErrorResponse(HttpStatusCode.InternalServerError, new HttpError() { { "status", "failed" }, { "message", ex.Message } });
            }
        }

我的CustomMultipartFormDataStreamProvider类就像,

public class CustomMultipartFormDataStreamProvider : MultipartFormDataStreamProvider
    {
        public CustomMultipartFormDataStreamProvider(string path)
            : base(path)
        { }

        public override string GetLocalFileName(System.Net.Http.Headers.HttpContentHeaders headers)
        {
            var name = !string.IsNullOrWhiteSpace(headers.ContentDisposition.FileName) ? DateTime.Now.ToString("MM-dd-yyyy-hh-mm-ss")+"_"+headers.ContentDisposition.FileName : "NoName";
            return name.Replace("\"", string.Empty); 
        }
    }

以上程序很好地将文件保存到上述文件夹中。但是我需要在成功上传图像后将上传的文件名存储到我的数据库表中。成功上传后如何获取发布文件的文件名。请指导我。

1 个答案:

答案 0 :(得分:0)

您可以获得如下文件名:

var task = Request.Content.ReadAsMultipartAsync(streamProvider).ContinueWith(
                    t =>
                    {
                        if (t.IsFaulted || t.IsCanceled)
                            throw new HttpResponseException(HttpStatusCode.InternalServerError);


            CustomMultipartFormDataStreamProvider resultProvider = t.Result;
            string fileName = t.FileData.First().LocalFileName;
                    }
                );