Kaynağa Gözat

[WebApiUtils] Added save uploaded file

develop
Robin Thoni 9 yıl önce
ebeveyn
işleme
51f5b3c0cb
1 değiştirilmiş dosya ile 52 ekleme ve 1 silme
  1. 52
    1
      WebApiUtils/BusinessManager/BMRHandler.cs

+ 52
- 1
WebApiUtils/BusinessManager/BMRHandler.cs Dosyayı Görüntüle

@@ -1,5 +1,11 @@
1
-using System.Net;
1
+using System;
2
+using System.Collections.Generic;
3
+using System.IO;
4
+using System.Linq;
5
+using System.Net;
2 6
 using System.Net.Http;
7
+using System.Threading;
8
+using System.Threading.Tasks;
3 9
 using System.Web.Http;
4 10
 using iiie.Logs.DataAccess;
5 11
 using iiie.Logs.DBO;
@@ -65,5 +71,50 @@ namespace iiie.WebApiUtils.BusinessManager
65 71
             var msg = Request.CreateErrorResponse(ResultStatusToHttp(result.Status), OpResultToString(result));
66 72
             throw new HttpResponseException(msg);
67 73
         }
74
+
75
+        /// <summary>
76
+        /// Save the uploaded file to the temp dir
77
+        /// </summary>
78
+        /// <returns>The file path</returns>
79
+        public async Task<OpResult<string>> SaveFileToTemp()
80
+        {
81
+            if (!Request.Content.IsMimeMultipartContent())
82
+            {
83
+                return OpResult<string>.Error(ResultStatus.InputError, "Bad content type", "");
84
+            }
85
+            IEnumerable<HttpContent> parts = null;
86
+            try
87
+            {
88
+                Task.Factory.StartNew(() => parts = Request.Content.ReadAsMultipartAsync().Result.Contents,
89
+                        CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default).Wait();
90
+            }
91
+            catch (Exception e)
92
+            {
93
+                return OpResult<string>.Error(ResultStatus.InputError, e, "Failed to read uploaded file");
94
+            }
95
+            HttpContent file = parts.FirstOrDefault();
96
+            if (file == null)
97
+            {
98
+                return OpResult<string>.Error(ResultStatus.InputError, "No uploaded file", "");
99
+            }
100
+            try
101
+            {
102
+                var path = Path.GetTempFileName();
103
+                using (var memoryStream = new MemoryStream(await file.ReadAsByteArrayAsync()))
104
+                {
105
+                    using (var streamWriter = new FileStream(path, FileMode.OpenOrCreate))
106
+                    {
107
+                        memoryStream.WriteTo(streamWriter);
108
+                        memoryStream.Close();
109
+                        streamWriter.Close();
110
+                    }
111
+                }
112
+                return OpResult<string>.Ok(path);
113
+            }
114
+            catch (Exception e)
115
+            {
116
+                return OpResult<string>.Error(ResultStatus.InputError, e, "Failed to write uploaded file");
117
+            }
118
+        }
68 119
     }
69 120
 }

Loading…
İptal
Kaydet