作者gn00595067 (天佑)
看板C_Sharp
标题[问题] MVC上传档案到AWS S3
时间Tue Jun 7 22:01:57 2016
小弟是程式新手想研究MVC上传S3功能,
nuget载完awssdk後,
试做了一个controller跟一个view想传档案
using Amazon.S3;
using Amazon.S3.Model;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace WebApplication17.Controllers
{
public class S3Controller : Controller
{
private static readonly string _awsAccessKey =
ConfigurationManager.AppSettings["AKxxxxxxxxxxxxxxxx"];
private static readonly string _awsSecretKey =
ConfigurationManager.AppSettings["Nfasxxxxxxxxxxxx"];
private static readonly string _bucketName =
ConfigurationManager.AppSettings["joxxxxxxx"];
public ActionResult UploadToS3()
{
return View();
}
[HttpPost]
public ActionResult UploadToS3(HttpPostedFileBase file)
{
try
{
IAmazonS3 client;
using (client = Amazon.AWSClientFactory.CreateAmazonS3Client(
_awsAccessKey, _awsSecretKey, Amazon.RegionEndpoint.APNortheast1))
{
var request = new PutObjectRequest()
{
BucketName = _bucketName,
CannedACL = S3CannedACL.PublicRead,//PERMISSION TO FILE PUBLIC ACCESIBLE
Key = string.Format("UPLOADS/{0}", file.FileName),
InputStream = file.InputStream,//SEND THE FILE STREAM
};
client.PutObject(request);
}
}
catch (Exception ex)
{
}
return View();
}
}
}
以下是view
@{
ViewBag.Title = "UploadToS3";
}
<h2>UploadToS3</h2>
<form action="@Url.Action("UploadToS3")" method="post"
enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="file" id="file" />
<input type="submit" />
</form>
可是不论如何都无法上传
拿掉catch会报错[AmazonS3Exception: The bucket you are attempting to access must be
addressed using the specified endpoint.
Please send all future requests to this endpoint.]
然後最後就显示[HttpErrorResponseException: 已发生类型 'Amazon.Runtime.Internal.
HttpErrorResponseException' 的例外状况。]
查了一天都还是卡在同一个地方,请高手相救~
感激万分!!
--
※ 发信站: 批踢踢实业坊(ptt.cc), 来自: 219.85.195.202
※ 文章网址: https://webptt.com/cn.aspx?n=bbs/C_Sharp/M.1465308120.A.D23.html
1F:→ KK2653: RegionEndPoint确定跟bucket设置的地区是一样的吗? 06/08 12:58
bucket设置在东京 和RegionEndPoint是一样的,我有试其他Region很多都一样错,
只有US-east1有特别反应,但每次都显示AmazoneS3Exception:access denid的error
试着在aws上加了几个access all action的policy 都没用
※ 编辑: gn00595067 (1.161.10.140), 06/08/2016 13:42:36
2F:→ KK2653: 虽然我手边没有MVC的环境,但我刚才使用form测试上传後, 06/09 21:08
3F:→ KK2653: 发现加了CannedACL此参数也会出现Access denied 的讯息, 06/09 21:08
4F:→ KK2653: 拿到後就可以上传成功了,不确定你的状况拿掉此参数後是否 06/09 21:08
5F:→ KK2653: 可行? 06/09 21:08
6F:→ gn00595067: 我最後发现我是犯了低级错误,一开始宣告的三个变数 06/11 01:09
7F:→ gn00595067: 没抓到值, 直接把key跟bucketname字串塞进方法里 06/11 01:10
8F:→ gn00595067: 就上传成功了 有没有设CannedACL我发现都可以 06/11 01:11
9F:→ gn00595067: 感谢K大的热心帮忙!!! 有人支持真的很令人感动! 06/11 01:13