Upload files not working when deploying in the IIS but during on development mode it's working perfectly. The destination folder is located in the another computer, let's say the Server itself. My concern relies only on the IIS deployment. I find so many topic related on Virtual Directory but I can't figure out how to manage it. Can anyone figure out how deal with uploading in another computer while the project is deployed in IIS. Your help is highly appreciated! Thanks!
[HttpPost]
public async Task<HttpResponseMessage> Post()
{
if (!Request.Content.IsMimeMultipartContent())
{
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
}
//assuming that appsetting.isprod is set to true
var root = AppSetting.IsProd ? @"\\172.16.174.2\c$\Resources" : HttpContext.Current.Server.MapPath("~/Resources/Uploads");
if (Directory.Exists(root) == false)
{
Directory.CreateDirectory(root);
}
CustomMultipartFormDataStreamProvider provider = new CustomMultipartFormDataStreamProvider(root);
try
{
// Read all contents of multipart message into CustomMultipartFormDataStreamProvider.
var results = await Request.Content.ReadAsMultipartAsync(provider);
var data = results.FormData["model"];
IbItemModel model = new System.Web.Script.Serialization.JavaScriptSerializer().Deserialize<IbItemModel>(data);
string filename = provider.FileData[0].LocalFileName;
var msg = "";
var supportedTypes = new[] { "txt", "csv" };
var fileExt = System.IO.Path.GetExtension(filename).Substring(1).ToLower();
if (!supportedTypes.Contains(fileExt))
{
msg += "File Extension Is InValid - Only Upload txt/csv File";
return Request.CreateResponse(HttpStatusCode.BadRequest, msg);
}
else
{
//success
}
}
catch (System.Exception e)
{
return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e);
}
}
public class CustomMultipartFormDataStreamProvider : MultipartFormDataStreamProvider
{
public CustomMultipartFormDataStreamProvider(string path) : base(path) { }
public override string GetLocalFileName(HttpContentHeaders headers)
{
var file = headers.ContentDisposition.FileName.Replace("\"", string.Empty);
return "IB-" + Guid.NewGuid().ToString("N").Substring(0, 8) + "-" + Path.GetFileName(file);
}
}
When deploying in IIS below message is occured.
{"Message":"An error has occurred.","ExceptionMessage":"Access to the path '\\172.16.174.2\c$\Resources' is denied.","ExceptionType":"System.UnauthorizedAccessException","StackTrace":" at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)\r\n at System.IO.Directory.InternalCreateDirectory(String fullPath, String path, Object dirSecurityObj, Boolean checkHost)\r\n at System.IO.Directory.InternalCreateDirectoryHelper(String path, Boolean checkHost)\r\n at WebApp.Controllers.api.IbItemController.