附加计数器,用于上传文件C#

时间:2018-11-09 19:21:34

标签: c# asp.net asyncfileupload

在保存上传的文件时,我需要在文件上附加计数器编号,例如客户端上传2个文件imagex.jpg,imagey.jpg

我想将它们另存为Client_UPI_1.jpg,Client_UPI_2.jpg

下面是我正在使用的代码

public class CustomMultipartFormDataStreamProvider : MultipartFormDataStreamProvider
{
    string _filename = null;
    public CustomMultipartFormDataStreamProvider(string path,string filename) : base(path) { _filename = filename; }

    public override Stream GetStream(HttpContent parent, HttpContentHeaders headers)
    {
        Logger.LogMessage(LogType.Debug, "GetStream Start");
        var fileExtension = Path.GetExtension(headers.ContentDisposition.FileName.Replace("\"", ""));
        Logger.LogMessage(LogType.Debug, "GetStream complete");
        return base.GetStream(parent, headers);
    }

    public override string GetLocalFileName(HttpContentHeaders headers)
    {
        ContentDispositionHeaderValue disposition = headers.ContentDisposition;
        string filename = (disposition != null && disposition.FileName != null) ? disposition.FileName : String.Empty;
        string extension = Path.GetExtension(filename.Replace("\"", ""));
        return String.Format(CultureInfo.InvariantCulture, "{0}", (_filename));
    }

  }

准备要在其中加载多部分表单数据的CustomMultipartFormDataStreamProvider

string fileUploadPath = Path.Combine(ConfigHelper.FILE_UPLOAD_LOCATION);
int counter = 0;
string filename = "Client_UPI_" + counter + ".jpg"; // NEED TO UPDATE THE COUNTER SO THAT FILE NAME A SEQUENCE NUMBER
CustomMultipartFormDataStreamProvider provider = new CustomMultipartFormDataStreamProvider(fileUploadPath,filename);

var task = request.Content.ReadAsMultipartAsync(provider).
    ContinueWith<HttpResponseMessage>(o =>
    {
         //some logic
    }
);
return task;

当前我所有的文件名都保存为“ Client_UPI_0.jpg”,我想根据文件的顺序更新计数器编号,例如file1将为“ Client_UPI_1.jpg”,file2将为“ Client_UPI_2.jpg”,依此类推

0 个答案:

没有答案