文件上传复合C1中的Razor函数

时间:2013-11-14 08:47:25

标签: asp.net razor c1-cms

我正在尝试创建一个剃须刀功能,允许用户创建文件上传表单。

该功能的参数是:

  • ContentPath - 将存储文件的服务器上的路径
  • FilePrefix - 可选前缀
  • FileSuffix - 可选后缀

我想知道这样的事情是否已经完成了? 如果不是,我似乎可以理解表格贴在哪里? reali进行上传的代码在哪里?

这是我到目前为止所做的。

@inherits RazorFunction

@functions {
    public override string FunctionDescription
    {
        get  { return "This is a file upload component."; }
    }

    [FunctionParameter(Label="Content Path", Help="Relative path of the folder that the files sholud be sotred in.", DefaultValue = "/Uploads")]
    public string ContentPath { get; set; }

    [FunctionParameter(Label = "File Prefix ", Help = "A prefix to append to the uploaded file.", DefaultValue = "")]
    public string FilePrefix { get; set; }

    [FunctionParameter(Label = "File Suffix ", Help = "A suffix to append to the uploaded file (befire the extention).", DefaultValue = "")]
    public string FileSuffix { get; set; }
}

<html xmlns="http://www.w3.org/1999/xhtml" xmlns:f="http://www.composite.net/ns/function/1.0">
    <head>
        @* script, css etc. you add in this head section end up in the head on the rendered page *@
    </head>
    <body>
        <form method="post" enctype="multipart/form-data" action="/Controller?">
            <input type="file" name="files[]" id="files[]" multiple="multiple" />
            <input type="submit" value="Upload files"/>
        </form>
    </body>
</html>

1 个答案:

答案 0 :(得分:1)

只需将表单的action-attribute保留为空,并在Razor文件的顶部添加以下代码

@{
    if (IsPost) 
    {
        foreach (HttpPostedFile file in Request.Files)
        {
            var fileName = FilePrefix + file.FileName;
            fileName = Path.GetFileNameWithoutExtension(fileName) + FileSuffix + Path.GetExtension(file.FileName);
            var path = Path.Combine(ContentPath, fileName);

            file.SaveAs(path);
        }
    }
}