[問題] MVC上傳檔案到AWS S3

看板C_Sharp作者 (天佑)時間8年前 (2016/06/07 22:02), 8年前編輯推噓0(009)
留言9則, 2人參與, 最新討論串1/1
小弟是程式新手想研究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://www.ptt.cc/bbs/C_Sharp/M.1465308120.A.D23.html

06/08 12:58, , 1F
RegionEndPoint確定跟bucket設置的地區是一樣的嗎?
06/08 12:58, 1F
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

06/09 21:08, , 2F
雖然我手邊沒有MVC的環境,但我剛才使用form測試上傳後,
06/09 21:08, 2F

06/09 21:08, , 3F
發現加了CannedACL此參數也會出現Access denied 的訊息,
06/09 21:08, 3F

06/09 21:08, , 4F
拿到後就可以上傳成功了,不確定你的狀況拿掉此參數後是否
06/09 21:08, 4F

06/09 21:08, , 5F
可行?
06/09 21:08, 5F

06/11 01:09, , 6F
我最後發現我是犯了低級錯誤,一開始宣告的三個變數
06/11 01:09, 6F

06/11 01:10, , 7F
沒抓到值, 直接把key跟bucketname字串塞進方法裡
06/11 01:10, 7F

06/11 01:11, , 8F
就上傳成功了 有沒有設CannedACL我發現都可以
06/11 01:11, 8F

06/11 01:13, , 9F
感謝K大的熱心幫忙!!! 有人支持真的很令人感動!
06/11 01:13, 9F
文章代碼(AID): #1NLjFOqZ (C_Sharp)