-2

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.

Mel Zen
  • 53
  • 1
  • 4
  • What does `Upload files not working` mean? How did you try to upload? With a `FileUpload` control? WebClient? Is there an error message? An exception? Until recently all ASP.NET applications were deployed to IIS so it's not that IIS can't handle file uploading. Something is wrong with the code or the configuration but people can't guess what it may be – Panagiotis Kanavos Jul 30 '18 at 10:20
  • This question is far too broad. There's no problem description, no code... – jAC Jul 30 '18 at 10:21
  • General users do not have permission to read/write files to the server. When a user runs an app from a server the files are saved on a different File System that is not on the Server. – jdweng Jul 30 '18 at 10:25
  • the file uploading is working perfectly but when deploying the program in IIS, error occurred "Access to the path is denied" – Mel Zen Jul 30 '18 at 10:29
  • If you want to write to another machine, you need the appropriate permissions to do so. See duplicate. – CodeCaster Jul 30 '18 at 10:32

1 Answers1

0

Here's an example of what I use to upload files to a folder.

First of all create a folder in your asp.net project for uploaded files, in so doing you'll avoid authorization issues on external folders with IIS (in this case, I created a subfolder named "uploads" in the App_Data folder)

    [HttpPost]
    public ActionResult Upload(HttpPostedFileBase filebase)
    {
        try
        {
            string fileName = string.Empty;
            string path; 
            if (filebase.ContentLength > 0)
            {
                fileName = Path.GetFileName(filebase.FileName);

                path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
                filebase.SaveAs(path);
                // Do stuff with the uploaded file
            }
        }
        catch (Exception){
            // Do whatever necessary to deal with the exception
        }

        return RedirectToAction("Index");

    }

Server.MapPath("~/App_Data/uploads") makes sure you get the right path once your application is published.

PS : If you write a class to deal with the uploaded files, you might want to implement IDisposable to delete the uploaded file or move it to another folder.

PS2 : you might want to implement logging if something goes wrong. I use NLog

Der_Devil
  • 21
  • 1
  • 4
  • Stack Overflow is not a snippet sharing website. That this code works for your scenario doesn't mean it'll work for the OP. We're here to answer specific questions with specific solutions. – CodeCaster Jul 30 '18 at 10:31
  • my path is located in another server. – Mel Zen Jul 30 '18 at 10:31