C# 管理面板的文件管理部分
我正在为我的客户开发一个CRM Web应用程序。它包括客户管理、支付等 我使用的技术包括:C# 管理面板的文件管理部分,c#,.net,asp.net-mvc,twitter-bootstrap,cloud-storage,C#,.net,Asp.net Mvc,Twitter Bootstrap,Cloud Storage,我正在为我的客户开发一个CRM Web应用程序。它包括客户管理、支付等 我使用的技术包括: ASP.NETMVC5 实体框架6 .NET Framework 4.5.2 引导程序3 现在,我的客户希望在Web应用程序中添加一个类似Dropbox的云文件存储。它应该允许上传/删除文件和文件夹(对于管理员),并且应该允许普通用户下载它们 我认为有一些很好的完整解决方案,所以我不会重新发明轮子。最好是开源和免费的。我正在寻找一个模块,我可以只设置和添加到我现有的应用程序 更新 我想是社区误会了我
- ASP.NETMVC5
- 实体框架6
- .NET Framework 4.5.2
- 引导程序3
更新 我想是社区误会了我。我不是在寻找一个真正繁重的文件管理解决方案。我们需要的是像马苏德·比马尔建议的那样。但我正在寻找更小更简单的东西 我只是不想重新发明轮子,从头开始编写代码对我来说有点无聊 我相信已经有人开发了这个功能 同样,解决方案应该只允许:
- 将文件上载到本地文件夹
- 从本地文件夹中删除文件
- 在本地文件夹中创建文件夹
- 删除本地文件夹中的文件夹
我的客户会偶尔使用它,上传的文件不会超过20个。可能会删除它们并不时上传新的内容。就是这样。我用了这个,用elFinder库构建的 文件管理器,带有ELFinder.Net。 支持目录,PDF文件,权限,漂亮的用户界面 我对它完全满意 套餐信息:
<package id="bootstrap" version="3.0.0" targetFramework="net45" />
<package id="Microsoft.AspNet.Mvc" version="5.2.3" targetFramework="net45" />
真正重新发明轮子是很棘手的,但是使用第三方软件包总是有限制的 我在AmazonWeb服务中使用Bucket S3,由于文件的访问是通过凭据进行的,因此在上载有访问权限的用户时,可以通过写入数据库来轻松限制对文件的访问 下面是一个上载和下载代码的示例 您需要安装AWS SDK Nuget软件包 与创建凭据的说明链接 我希望这能在某种程度上有所帮助
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();
}
使用Amazon.S3;
使用Amazon.S3.0模型;
公共异步任务上载(IFormFile)
{
BasicAWSCredentials awsCredentials=新的BasicAWSCredentials(“accessKey”、“secretKey”);
IAmazonS3 clientAws=新亚马逊3客户机(awsCredentials,Amazon.RegionEndpoint.EUCentral1);
字符串urlTemp=Path.GetTempFileName();
字符串扩展名=Path.GetExtension(file.FileName);
Guid=Guid.NewGuid();
字符串nameFile=guid+扩展名;
字符串contentType=file.contentType;
使用(var fileStream=newfilestream(urltmp,FileMode.Create))
{
等待file.CopyToAsync(fileStream);
}
尝试
{
//简单对象输入
使用(客户端)
{
var request=new PutObjectRequest()
{
BucketName=“yourback”,
Key=nameFile,
FilePath=urlTemp,
ContentType=ContentType
};
var response=await clientAws.PutObjectAsync(请求);
//在数据库中写入
}
}
捕获(AmazonS3Exception AmazonS3Exception)
{
如果(amazonS3Exception.ErrorCode!=null&&
(amazonS3Exception.ErrorCode.Equals(“InvalidAccessKeyId”)||
amazonS3Exception.ErrorCode.Equals(“InvalidSecurity”))
{
Console.WriteLine(“请检查提供的AWS凭据”);
WriteLine(“如果您尚未注册AmazonS3,请访问http://aws.amazon.com/s3");
}
其他的
{
WriteLine(“在写入对象时消息“{0}”发生错误”,amazonS3Exception.message);
}
}
返回Ok();
}
公共异步任务下载(字符串文件)
{
尝试
{
BasicAWSCredentials awsCredentials=新的BasicAWSCredentials(“accessKey”、“secretKey”);
IAmazonS3 clientAws=新亚马逊3客户机(awsCredentials,Amazon.RegionEndpoint.EUCentral1);
GetObjectResponse=新建GetObjectResponse();
字符串urlTemp=Path.GetTempPath();
Guid=Guid.NewGuid();
字符串nameFile=guid+“.pdf”;
尝试
{
//简单对象输入
使用(客户端)
{
GetObjectRequest=新建GetObjectRequest();
request.BucketName=“yourBucket”;
request.Key=文件;
response=wait clientAws.GetObjectAsync(请求);
CancellationTokenSource=新的CancellationTokenSource();
CancellationToken=source.token;
等待响应。writeResponseStreamofileAsync(urlTemp+nameFile,true,令牌);
var path=urlTemp+nameFile;
var memory=newmemoryStream();
使用(var stream=newfilestream(路径,FileMode.Open))
{
等待流。CopyToAsync(内存);
}
记忆位置=0;
var fsResult=newfilestreamresult(内存,“应用程序/pdf”);
返回结果;
}
}
捕获(AmazonS3Exception AmazonS3Exception)
{
如果(amazonS3Exception.ErrorCode!=null&&
(amazonS3Exception.ErrorCode.Equals(“InvalidAccessKeyId”)||
amazonS3Exception.ErrorCode.Equals(“InvalidSecurity”))
{
Console.WriteLine(“请检查提供的AWS凭据”);
WriteLine(“如果您尚未注册AmazonS3,请访问http://aws.amazon.com/s3");
}
其他的
{
Console.WriteLine(“th发生错误
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>
}