· 9 years ago · Jan 25, 2017, 03:00 PM
1 public async Task<ActionResult> UploadFiles()
2 {
3 try
4 {
5 FileStorage.FileStorageResult myObj;
6 string fileName = string.Empty;
7 foreach (string fileTemp in Request.Files)
8 {
9 var fileContent = Request.Files[fileTemp];
10 var uploader = Request.Form["uploader"] != null ? Request.Form["uploader"].ToString() + ".screenshot" : "logo";
11 fileName = uploader + DateTime.Now.Ticks.ToString() + fileContent.FileName;
12
13 if (fileContent != null && fileContent.ContentLength > 0)
14 {
15 byte[] fileBuffer = new byte[fileContent.InputStream.Length];
16 for (int totalBytesCopied = 0; totalBytesCopied < fileContent.InputStream.Length;)
17 {
18 totalBytesCopied += fileContent.InputStream.Read(fileBuffer, totalBytesCopied, Convert.ToInt32(fileContent.InputStream.Length) - totalBytesCopied);
19 }
20 this.fileInfo = new FileStorage.FileInfo();
21 this.fileInfo.KeyName = fileName;
22 this.fileInfo.AWSAccessInfo = new FileStorage.AWSAccessInformation { AccessKey = LocalConfiguration.AccessKey, SecretKey = LocalConfiguration.SecretKey, BucketName = LocalConfiguration.BucketName, ProfileName = LocalConfiguration.ProfileName};
23 using (MultipartFormDataContent mpartContent = new MultipartFormDataContent())
24 {
25 mpartContent.Add(new StringContent(JsonConvert.SerializeObject(this.fileInfo)), "FileInfo");
26 mpartContent.Add(new ByteArrayContent(fileBuffer), "FileContent");
27 string responseString;
28 string uri = LocalConfiguration.FileStorageBaseURL + LocalConfiguration.UploadURL;
29
30 HttpResponseMessage httpMessage = await this.client.PostAsync(uri, mpartContent);
31 responseString = await httpMessage.Content.ReadAsStringAsync();
32 myObj = JsonConvert.DeserializeObject<FileStorage.FileStorageResult>(responseString);
33 }
34 }
35
36 var createmediadto = new CreateMediaDTO()
37 {
38 Url = null,
39 MediaKey = fileName
40 };
41 this.AppendBearerToken();
42 string mediaId = string.Empty;
43 string endpoint = LocalConfiguration.InsertMediaApiUrl + this.IsoUserId;
44 var content = new StringContent(JsonConvert.SerializeObject(createmediadto).ToString(), Encoding.UTF8, "application/json");
45
46 var response = this.client.PostAsync(endpoint, content).Result;
47
48 var responseStream = response.Content.ReadAsStreamAsync().Result;
49 if(responseStream !=null)
50 {
51 using (var reader = new StreamReader(responseStream))
52 {
53 mediaId = reader.ReadToEnd();
54 }
55 }
56 return this.Content(mediaId);
57 }
58 }
59 catch (Exception ex)
60 {
61 this.logger.Error("Error Occured while uploading the file", ex);
62 }
63 return this.Content(string.Empty);
64 }