gpt4 book ai didi

c# - 使用 asp.net MVC 拖放上传到 aws s3

转载 作者:太空宇宙 更新时间:2023-11-03 15:01:06 25 4
gpt4 key购买 nike

我在将文件上传到我正在处理的基本 mvc 项目时遇到了一些问题...我有一个拖放功能,我想连接到 aws s3。我可以将文件放入当前应用程序的本地文件夹中.. 并按照此处的步骤操作 -> upload a file to amazon s3 super easy using c sharp -- 成功上传单个特定文件。但是,我无法将两者结合起来,以便我拖/放的文件最终会出现在我的存储桶中。

以下是我迄今为止的所有代码:

索引

@{
ViewBag.Title = "Index";
}

<h2>Drag & Drop File Upload</h2>
<div id="dropArea">
Drop your files here
</div>
<h4>Uploaded Files: </h4>
<ul class="list-group" id="uploadList">

</ul>

<style>
#dropArea {
background-image: url("http://xx.png");
background-repeat: no-repeat;
background-position: center;
background-color:#fff;
border: black dashed 1px;
height: 500px;
text-align: center;
color: black;
}
.active-drop{
background:#739cfb !important;
border:solid 2px blue !important;
opacity:.5;
color:black !important;
}
</style>

@section Scripts {
<script src="~/Scripts/jquery.filedrop.js"></script>
<script type="text/javascript">
$(function () {
$('#dropArea').filedrop({
url: '@Url.Action("UploadFiles")',
allowedfiletypes: ['image/jpeg', 'image/png', 'image/gif'],
allowedfileextensions: ['.jpg', '.jpeg', '.png', '.gif'],
paramname: 'files',
maxfiles: 5,
maxfilesize: 5, // in MB
dragOver: function () {
$('#dropArea').addClass('active-drop');

},
dragLeave: function () {
$('#dropArea').removeClass('active-drop');
},
drop: function () {
$('#dropArea').removeClass('active-drop');
},
afterAll: function (e) {
$('#dropArea').html('file(s) uploaded successfully');

},
uploadFinished: function (i, file, response, time) {
$('#uploadList').append('<li class="list-group-item">'+file.name+'</li>')
}
})
})
</script>
}

家庭 Controller .cs

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MVCDragDrop.Controllers
{
public class HomeController : Controller
{
// GET: Home
public ActionResult Index()
{
AmazonS3Uploader amazonS3 = new AmazonS3Uploader();

amazonS3.UploadFile();

return View();
}

[HttpPost]
public ActionResult UploadFiles(IEnumerable<HttpPostedFileBase> files)
{

foreach (var file in files) {
string filePath = Guid.NewGuid() + Path.GetExtension(file.FileName);
file.SaveAs(Path.Combine(Server.MapPath("~/UploadedFiles"), filePath));
}

return Json("file uploaded successfully");
}
}
}

AmazonS3Uploader.cs

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

namespace MVCDragDrop
{
public class AmazonS3Uploader
{
private string bucketName = "xxxxx";
private string keyName = "";
private string filePath = "";

public void UploadFile()
{
var client = new AmazonS3Client(Amazon.RegionEndpoint.USEast1);

try {
PutObjectRequest putRequest = new PutObjectRequest {
BucketName = bucketName,
Key = keyName,
FilePath = filePath,
ContentType = "plain/text"
};

PutObjectResponse response = client.PutObject(putRequest);
}
catch (AmazonS3Exception amazonS3Exception) {
if (amazonS3Exception.ErrorCode != null &&
(amazonS3Exception.ErrorCode.Equals("InvalidAccessKeyId")
||
amazonS3Exception.ErrorCode.Equals("InvalidSecurity"))) {
throw new Exception("Check the provided AWS Credentials.");
} else {
//throw new Exception("Error occurred: " + amazonS3Exception.Message);
}
}
}
}
}

我的 webconfig 文件也设置了正确的 s3 key / secret /配置文件名称。

如有任何帮助,我们将不胜感激!

谢谢

最佳答案

我将按照您发布问题的顺序开始。

Index.cshtml

1) 请验证您在 url: '@Url.Action("UploadFiles")' 中引用的 URL 是否正确。我相信它应该是 url: '@Url.Action("UploadFiles", "Home")'

2) 请验证您是否通过脚本标签添加了 jquery。

HomeController.cs

1) 您的 Index 函数应该只返回一个 View 。

2) 在构造函数中实例化一个新的 AmazonS3Uploader。

3) 将所有文件路径保存在列表中,遍历它们并将每个路径传递给 amazonS3.UploadFile(path)` 以上传到 S3

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MVCDragDrop.Controllers
{
public class HomeController : Controller
{
private AmazonS3Uploader amazonS3;

public HomeController()
{
amazonS3 = new AmazonS3Uploader();
}
// GET: Home
public ActionResult Index()
{
return View();
}

[HttpPost]
public ActionResult UploadFiles(IEnumerable<HttpPostedFileBase> files)
{
List<string> paths = new List<string>();

foreach (var file in files) {
string filePath = Guid.NewGuid() + Path.GetExtension(file.FileName);
string destPath = Path.Combine(Server.MapPath("~/UploadedFiles"), filePath);
paths.Add(destPath)
file.SaveAs(destPath);
}

foreach(var path in paths){
amazonS3.UploadFile(path);
}

return Json("file uploaded successfully");
}
}
}

AmazonS3Uploader.cs

1) 在构造函数中实例化客户端对象。

2) 更改您的 UploadFile() 方法以接受文件路径并在 PutObjectRequest 中使用该路径

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

namespace MVCDragDrop
{
public class AmazonS3Uploader
{
private string bucketName = "xxxxx";
private string keyName = "";
private AmazonS3Client client;

public AmazonS3Uploader()
{
client = new AmazonS3Client(Amazon.RegionEndpoint.USEast1);
}

public void UploadFile(string filePath)
{

try {
PutObjectRequest putRequest = new PutObjectRequest {
BucketName = bucketName,
Key = keyName,
FilePath = filePath,
ContentType = "plain/text"
};

PutObjectResponse response = client.PutObject(putRequest);
}
catch (AmazonS3Exception amazonS3Exception) {
if (amazonS3Exception.ErrorCode != null &&
(amazonS3Exception.ErrorCode.Equals("InvalidAccessKeyId")
||
amazonS3Exception.ErrorCode.Equals("InvalidSecurity"))) {
throw new Exception("Check the provided AWS Credentials.");
} else {
//throw new Exception("Error occurred: " + amazonS3Exception.Message);
}
}
}
}
}

希望我能帮上忙:)

关于c# - 使用 asp.net MVC 拖放上传到 aws s3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46084082/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com