Securely Upload Files With C# Azure Functions And Javascript

20 Jul 2023 Balmiki Mandal 0 C# (C Sharp)

Using File Uploads with JS and C# Azure Functions

Creating file uploads for applications can be a daunting task, but with the help of JavaScript and C# Azure Functions, it doesn't have to be. In this tutorial, we will show you how to easily use these two technologies to create efficient and secure file uploads for your applications.

Preparing Your Azure Function

The first step in creating your file uploads is to create an Azure Function that will receive the uploaded files. To do this, you'll first need to create a new Azure Function app in the Azure portal. Once your function app has been created, go into the editor and select “HTTP Trigger” as the trigger type. Be sure to set the access level to “Anonymous” so that anonymous users can upload files.

Next, you'll need to add the code necessary to handle the file uploads. In our example, we are using C# to create the code. The code should look something like this:

public static async Task<IActionResult> Run(
    [HttpTrigger(AuthorizationLevel.Anonymous, "post")]
    HttpRequest req,
    ILogger log)
{
    Stream stream = req.Body;
    var reader = new StreamReader(stream);
    var fileContents = reader.ReadToEnd();
 
    string path = await SaveFileAsync(fileContents);
    return (ActionResult)new OkObjectResult($"File uploaded successfully at {path}");
}

private static async Task<string> SaveFileAsync(string content)
{
    var path = Path.Combine("path/to/file/dir", "filename.ext");
    using (var writer = File.CreateText(path))
    {
        await writer.WriteAsync(content);
    }
    return path;
}

This code snippet will take in the request body and save it as a file with the specified name and extension in a folder of your choice. You can modify this code as needed to fit your needs.

Creating the JavaScript Client

Now that we have our Azure Function setup, we need to create the JavaScript client that will actually upload the files. We will use the Fetch API so that we can send a POST request to our Azure Function. Our code should look something like this:

async function uploadFile(file) {
  const formData = new FormData();
  formData.append("file", file);
 
  const response = await fetch("https://your-function-app.azurewebsites.net/api/fileupload", {
    method: "POST",
    body: formData
  });
 
  return response.json();
}

This code snippet will take in a file object, create a FormData object, add the file to that FormData object, and then send a POST request to your Azure Function with the FormData object as the payload. You can then process the response from the server and do whatever you need to do with the uploaded file.

Conclusion

By leveraging both JavaScript and C#, you can easily create a secure and efficient file upload system for your applications. Azure Functions provide a great way to quickly and easily setup an endpoint to receive and process the files, and the Fetch API allows us to easily send the files from the client side. Using these two technologies together, you can create a robust file upload system that helps your application remain secure and user friendly.

BY: Balmiki Mandal

Related Blogs

Post Comments.

Login to Post a Comment

No comments yet, Be the first to comment.