【发布时间】:2018-01-06 16:23:15
【问题描述】:
我已经为图片上传创建了一个 api。在这段代码中,我在本地文件夹和存储中下载了上传时间图像。但我现在需要更改我的代码并将此图像下载移动到 amzon s3 上。我在搜索时间找到了一个链接,但在这个链接中,静态图片是上传,我需要从文件上传控件浏览图片并在 amzon 服务器上下载。但我不知道该怎么做。请任何人如何做到这一点,然后请帮助我。下面列出了我的代码。并补充说我在下面尝试了这个代码。
这是我上传图片的api方法:
[HttpPost]
[Route("FileUpload")]
public HttpResponseMessage FileUpload(string FileUploadType)
{
try
{
var httpRequest = HttpContext.Current.Request;
if (httpRequest.Files.Count > 0)
{
foreach (string file in httpRequest.Files)
{
var postedFile = httpRequest.Files[file];
string fname = System.IO.Path.GetFileNameWithoutExtension(postedFile.FileName.ToString());
string extension = Path.GetExtension(postedFile.FileName);
Image img = null;
string newFileName = "";
newFileName = DateTime.Now.ToString("yyyyMMddhhmmssfff") + ".jpeg";
string path = ConfigurationManager.AppSettings["ImageUploadPath"].ToString();
string filePath = Path.Combine(path, newFileName);
SaveJpg(img, filePath);
return Request.CreateResponse(HttpStatusCode.OK, "Ok");
}
}
}
catch (Exception ex)
{
return ex;
}
return Request.CreateResponse(HttpStatusCode.OK, "Ok");
}
这是我的保存图片 api =>
public static void SaveJpg(Image image, string file_name, long compression = 60)
{
try
{
EncoderParameters encoder_params = new EncoderParameters(1);
encoder_params.Param[0] = new EncoderParameter(
System.Drawing.Imaging.Encoder.Quality, compression);
ImageCodecInfo image_codec_info =
GetEncoderInfo("image/jpeg");
image.Save(file_name, image_codec_info, encoder_params);
}
catch (Exception ex)
{
}
}
我已经尝试在服务器上上传静态图片的代码 =>
private string bucketName = "Xyz";
private string keyName = "abc.jpeg";
private string filePath = "C:\\Users\\I BALL\\Desktop\\image\\abc.jpeg";. // this image is store on server
public void UploadFile()
{
var client = new AmazonS3Client(Amazon.RegionEndpoint.USEast1);
try
{
PutObjectRequest putRequest = new PutObjectRequest
{
BucketName = bucketName,
Key = keyName,
FilePath = filePath,
ContentType = "text/plain"
};
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);
}
}
}
在这里我展示了我的代码,但我需要与我的代码保持一致,所以如何做到这一点,请任何知道如何做到这一点的人。
【问题讨论】:
-
我不禁认为互联网上已经有大量的例子表明docs.aws.amazon.com/AmazonS3/latest/dev/HLuploadFileDotNet.html和docs.aws.amazon.com/AmazonS3/latest/dev/…是一个好的开始
-
@matt_lethargic 我也找到了这个链接,但在这个链接中只提供静态图片并上传,但我希望 httppostedfilebase 使用服务器上的图片上传所以怎么办请帮助我你知道吗?
标签: c# image asp.net-web-api amazon-s3