管理面板的文件管理部分

时间:2019-01-10 10:20:18

标签: c# .net asp.net-mvc twitter-bootstrap cloud-storage

我正在为我的客户开发CRM Web应用程序。它包括客户管理,付款等。

我使用的技术:

  • ASP.NET MVC 5
  • EntityFramework 6
  • .NET Framework 4.5.2
  • 引导程序3

现在,我的客户希望将诸如Dropbox之类的云文件存储添加到Web应用程序。它应该允许上传/删除文件和文件夹(供管理员使用),并应允许普通用户下载它们。

我认为有一些很好的完整解决方案,所以我不会重新发明轮子。首选开源和免费。我正在寻找一个可以设置并添加到现有应用程序中的模块。


更新

我认为这样的社区弄错了我。我不是在寻找真正繁重的文件管理解决方案。需要的是Masoud Bimar建议的东西。但是我正在寻找更小,更简单的东西。

我只是不想重新发明轮子,让我从头开始编写代码有点无聊。

我确定有人已经开发了此功能。

同样,一个解决方案应该允许:

  • 将文件上传到本地文件夹
  • 从本地文件夹中删除文件
  • 在本地文件夹中创建文件夹
  • 删除本地文件夹中的文件夹

我的客户偶尔会使用它,并且只会上传不超过20个文件。也许删除它们并不时上传新的。就是这样。

3 个答案:

答案 0 :(得分:2)

真正重塑方向盘是很棘手的,但是使用3rd party软件包总是有局限性。

我在Amazon Web Services中使用Bucket S3,由于通过凭证访问文件,您可以在上载具有访问权限的用户时通过写入数据库来轻松限制对文件的访问。

以下是上传和下载代码的示例。

您将需要安装AWS开发工具包Nuget软件包。

https://aws.amazon.com/sdk-for-net/

带有创建凭证说明的链接

https://docs.aws.amazon.com/en/sdk-for-net/v2/developer-guide/net-dg-setup.html#net-dg-signup

我希望这可以有所帮助

using Amazon.S3;
using Amazon.S3.Model;

public async Task<IActionResult> Upload(IFormFile file)
{
    BasicAWSCredentials awsCredentials = new BasicAWSCredentials("accessKey", "secretKey");
    IAmazonS3 clientAws = new AmazonS3Client(awsCredentials, Amazon.RegionEndpoint.EUCentral1);
    string urlTemp = Path.GetTempFileName();
    string extension = Path.GetExtension(file.FileName);
    Guid guid = Guid.NewGuid();
    string nameFile = guid + extension;
    string contentType = file.ContentType;

    using (var fileStream = new FileStream(urlTemp, FileMode.Create))
    {
        await file.CopyToAsync(fileStream);
    }

    try
    {
        // simple object put
        using (clientAws)
        {
            var request = new PutObjectRequest()
            {
                BucketName = "yourbucket",
                Key = nameFile,
                FilePath = urlTemp,
                ContentType = contentType
            };
            var response = await clientAws.PutObjectAsync(request);

            //write in your db
        }
    }
    catch (AmazonS3Exception amazonS3Exception)
    {
        if (amazonS3Exception.ErrorCode != null &&
            (amazonS3Exception.ErrorCode.Equals("InvalidAccessKeyId") ||
            amazonS3Exception.ErrorCode.Equals("InvalidSecurity")))
        {
            Console.WriteLine("Please check the provided AWS Credentials.");
            Console.WriteLine("If you haven't signed up for Amazon S3, please visit http://aws.amazon.com/s3");
        }
        else
        {
            Console.WriteLine("An error occurred with the message '{0}' when writing an object", amazonS3Exception.Message);
        }
    }

    return Ok();
}

public async Task<IActionResult> Download(string file)
{
    try
    {
        BasicAWSCredentials awsCredentials = new BasicAWSCredentials("accessKey", "secretKey");
        IAmazonS3 clientAws = new AmazonS3Client(awsCredentials, Amazon.RegionEndpoint.EUCentral1);

        GetObjectResponse response = new GetObjectResponse();

        string urlTemp = Path.GetTempPath();
        Guid guid = Guid.NewGuid();
        string nameFile = guid + ".pdf";

        try
        {
            // simple object put
            using (clientAws)
            {
                GetObjectRequest request = new GetObjectRequest();

                request.BucketName = "yourBucket";
                request.Key = file;
                response = await clientAws.GetObjectAsync(request);
                CancellationTokenSource source = new CancellationTokenSource();
                CancellationToken token = source.Token;
                await response.WriteResponseStreamToFileAsync(urlTemp + nameFile, true, token);


                var path = urlTemp + nameFile;
                var memory = new MemoryStream();
                using (var stream = new FileStream(path, FileMode.Open))
                {
                    await stream.CopyToAsync(memory);
                }
                memory.Position = 0;

                var fsResult = new FileStreamResult(memory, "application/pdf");
                return fsResult;

            }

        }
        catch (AmazonS3Exception amazonS3Exception)
        {
            if (amazonS3Exception.ErrorCode != null &&
                (amazonS3Exception.ErrorCode.Equals("InvalidAccessKeyId") ||
                amazonS3Exception.ErrorCode.Equals("InvalidSecurity")))
            {
                Console.WriteLine("Please check the provided AWS Credentials.");
                Console.WriteLine("If you haven't signed up for Amazon S3, please visit http://aws.amazon.com/s3");
            }
            else
            {
                Console.WriteLine("An error occurred with the message '{0}' when writing an object", amazonS3Exception.Message);
            }

        }
    }
    catch (Exception ex)
    {
        //throw;
    }

    return View();
}

答案 1 :(得分:2)

以下是使用标准ASP.NET MVC控制器和动作,实体框架和强大的javascript库dropzone来使用AJAX上传多个文件的简单文件管理系统的示例。

每个客户都有一个文件列表,因此我们需要将此信息存储在数据库表中,这是模型:

public class FileUpload
{
    public int Id { get; set; }
    public int CustomerId { get; set; }
    public string Filename { get; set; }
    public string OriginalFilename { get; set; }
    public string ContentType { get; set; }
}

然后,控制器将处理文件的上载和下载等...

public class FileUploadController : Controller
{
    private SomeDbContext db = new SomeDbContext();

    // You should store the following settings in your Web.config or in your DB, I just put them here for demo purposes

    // This is the root folder where your files will be saved
    private string FilesRoot = @"c:\temp";

    // Accepted file types and maximum size, for security (it should match the settings in your view)
    private string[] AcceptedFiles = new string[] { ".jpg", ".png", ".doc" };
    private int MaxFileSizeMB = 10;

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult UploadFiles(int customerId)
    {
        foreach(string file in Request.Files)
        {
            var upload = Request.Files[file];

            if (!ValidateUpload(upload))
                return new HttpStatusCodeResult(HttpStatusCode.Forbidden);

            string filename = Guid.NewGuid().ToString() + Path.GetExtension(upload.FileName);

            // Save the file in FilesRoot/{CustomerId}/{GUID}
            string savePath = Path.Combine(FilesRoot, customerId.ToString());
            if (!Directory.Exists(savePath))
            {
                Directory.CreateDirectory(savePath);
            }

            upload.SaveAs(Path.Combine(savePath, filename));

            // Save file info to database
            var fileUpload = new FileUploadModel()
            {
                CustomerId = customerId,
                Filename = filename,
                OriginalFilename = upload.FileName,
                ContentType = upload.ContentType
            };

            db.FileUploads.Add(fileUpload);
            db.SaveChanges();
        }

        return new HttpStatusCodeResult(HttpStatusCode.OK);
    }

    private bool ValidateUpload(HttpPostedFileBase upload)
    {
        if (!AcceptedFiles.Contains(Path.GetExtension(upload.FileName)))
            return false;
        else if (upload.ContentLength > MaxFileSizeMB * 1048576)
            return false;

        return true;
    }

    public ActionResult DownloadFile(int id)
    {
        var fileUpload = db.FileUploads.FirstOrDefault(x => x.Id == id);
        if (fileUpload == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.NotFound);
        }

        string path = Path.Combine(FilesRoot, fileUpload.CustomerId.ToString(), fileUpload.Filename);

        byte[] fileContents = System.IO.File.ReadAllBytes(path);

        return File(fileContents, fileUpload.ContentType, fileUpload.OriginalFilename);
    }

    public ActionResult ListFiles(int customerId)
    {
        var files = db.FileUploads.Where(x => x.CustomerId == customerId);
        return View(files.ToList());
    }


    protected override void Dispose(bool disposing)
    {
        if (disposing)
        {
            db.Dispose();
        }
        base.Dispose(disposing);
    }
}

最后,这是上传文件的视图,您可能需要添加另一个视图以显示给定客户的文件列表,但这应该很简单。

@{
    ViewBag.Title = "Upload Files";
}

<div>
    <button id="selectFile">Click to Browse File</button>
</div>

@using (Html.BeginForm("UploadFiles", "FileUpload", FormMethod.Post, new { id = "uploadForm", @class = "dropzone dropzone-area" }))
{
    @Html.AntiForgeryToken()

    @Html.Hidden("CustomerId", 1)

    <div class="dz-message">Drop File Here To Upload</div>

    <div class="fallback">
        <input name="file" type="file" multiple />
    </div>
}


@section Scripts {
    <script src="@Url.Content("~/Scripts/dropzone.js")"></script>

    <script type="text/javascript">
        Dropzone.options.selectForm = {
            paramName: 'file',
            maxFilesize: 10,
            maxFiles: 10,
            acceptedFiles: '.jpg,.png,.doc,.pdf',
            addRemoveLinks: false
        };

        $('#selectFile').on('click', function () {
            $('#uploadForm').trigger('click');
        });
    </script>
}

答案 2 :(得分:0)

我用的是这个内置有elFinder库的。

文件管理器,带有ELFinder.Net。 支持目录,PDF文件,权限,尼斯UI。

我对此完全满意。

包装信息:

  <package id="bootstrap" version="3.0.0" targetFramework="net45" />
  <package id="Microsoft.AspNet.Mvc" version="5.2.3" targetFramework="net45" />

github repository