ASP.NET WebAPI更改文件名?

时间:2014-02-28 17:34:47

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

我正在尝试将图片的文件名更改为我在输入框username中发布的值。文件将上传到服务器,并且在覆盖GetLocalFileName后,文件名从“BodyPart_(xyz)”更改为原始文件名。如何将它们重命名为我在输入框中提供的值?

<form name="form1" method="post" enctype="multipart/form-data" action="api/poster/postformdata">
            <div class="row-fluid fileform">
                <div class="span3"><strong>Username:</strong></div>
                <input name="username" value="test" type="text" readonly/>
            </div>

            <div class="row-fluid fileform">
                <div class="span3"><strong>Poster:</strong></div>
                <div class="span4"><input name="posterFileName" ng-model="posterFileName" type="file" /></div>
            </div>

            <div class="row-fluid fileform">
                 <div class="span8"><input type="submit" value="Submit" class="btn btn-small btn-primary submitform" /></div>
            </div>
</form>

我已将我收到的值存储在newName变量中,但我对如何重命名服务器中的文件感到困惑。

public async Task<HttpResponseMessage> PostFormData()
            {
                if (!Request.Content.IsMimeMultipartContent())
                {
                    throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
                }

                string root = HttpContext.Current.Server.MapPath("~/App_Data");
                var provider = new MultipartFormDataStreamProvider(root);

                try
                {
                    await Request.Content.ReadAsMultipartAsync(provider);
                    // Show all the key-value pairs.
                    foreach (var key in provider.FormData.AllKeys)
                    {
                        foreach (var val in provider.FormData.GetValues(key))
                        {
                            Trace.WriteLine(string.Format("{0}: {1}", key, val));
                            newName = val;
                        }
                    }

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

            public class MyMultipartFormDataStreamProvider : MultipartFormDataStreamProvider
            {
                public MyMultipartFormDataStreamProvider(string path)
                    : base(path)
                {

                }

                public override string GetLocalFileName(System.Net.Http.Headers.HttpContentHeaders headers)
                {
                    string fileName;
                    if (!string.IsNullOrWhiteSpace(headers.ContentDisposition.FileName))
                    {
                        fileName = headers.ContentDisposition.FileName;
                    }
                    else
                    {
                        fileName = Guid.NewGuid().ToString() + ".data";
                    }
                    return fileName.Replace("\"", string.Empty);
                }
            }

1 个答案:

答案 0 :(得分:1)

一种方法是覆盖ExecutePostProcessingAsync方法,如下所示:

public override async Task ExecutePostProcessingAsync()
{
    await  base.ExecutePostProcessingAsync();

    // By this time the file would have been uploaded to the location you provided
    // and also the dictionaries like FormData and FileData would be populated with information
    // that you can use like below

    string targetFileName = FormData["username"];

    // get the uploaded file's name
    string currentFileName = FileData[0].LocalFileName;

    //TODO: rename the file
}