Abhay.Patil
Abhay.Patil

Reputation: 743

'HttpPostedFileBase' in Asp.Net Core 2.0

I'm recently working on a ReactJS app that's calling an API (developed with .NET Core 2.0).

My question is how to use HttpPostedFileBase in an .NET Core 2.0 API in order to get file content and save it in database.

Upvotes: 53

Views: 78273

Answers (5)

DS6604_28__
DS6604_28__

Reputation: 1

using System;
using System.Collections.Generic;
using System.IO;
using System.Web.Mvc;
using YourNamespace.Models;

namespace YourNamespace.Controllers
{
    public class HomeController : Controller
    {
        private static List<FileModel> uploadedFiles = new List<FileModel>();

        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public ActionResult UploadFile()
        {
            var model = new FileModel
            {
                Id = uploadedFiles.Count + 1,
                Name = Request.Form["Name"],
                PdfFile = Request.Files["PdfFile"]
            };

            if (ModelState.IsValid)
            {
                model.UploadFile();
                uploadedFiles.Add(model);
            }

            return View("Index", uploadedFiles);
        }

        public ActionResult ViewPdf(int id)
        {
            var fileModel = uploadedFiles.Find(f => f.Id == id);
            if (fileModel != null)
            {
                // Specify the directory where you want to retrieve the files
                string uploadDir = HttpContext.Server.MapPath("~/storeFile");
                string fileName = $"{fileModel.Id}_{fileModel.Name}.pdf";
                string filePath = Path.Combine(uploadDir, fileName);

                return File(filePath, "application/pdf", fileName);
            }

            return HttpNotFound();
        }
    }
}
using System;
using System.IO;
using System.Web;

namespace YourNamespace.Models
{
    public class FileModel
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public HttpPostedFileBase PdfFile { get; set; }
        public string Message { get; set; }

        public void UploadFile()
        {
            if (PdfFile != null && PdfFile.ContentLength > 0)
            {
                try
                {
                    // Specify the directory where you want to store the files
                    string uploadDir = HttpContext.Current.Server.MapPath("~/storeFile");
                    if (!Directory.Exists(uploadDir))
                    {
                        Directory.CreateDirectory(uploadDir);
                    }

                    // Save the file to the specified directory
                    string fileName = $"{Id}_{Name}.pdf";
                    string filePath = Path.Combine(uploadDir, fileName);
                    PdfFile.SaveAs(filePath);

                    Message = "File uploaded successfully.";
                }
                catch (Exception ex)
                {
                    Message = "Error uploading file: " + ex.Message;
                }
            }
            else
            {
                Message = "Please select a file.";
            }
        }
    }
}
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>File Upload</title>
</head>

<body>
    <h2>Uploaded Files</h2>

    <table border="1">
        <tr>
            <th>ID</th>
            <th>Name</th>
            <th>Actions</th>
        </tr>
        <script>
            var uploadedFiles = @Html.Raw(Json.Encode(Model));
            for (var i = 0; i < uploadedFiles.length; i++) {
                document.write('<tr>');
                document.write('<td>' + uploadedFiles[i].Id + '</td>');
                document.write('<td>' + uploadedFiles[i].Name + '</td>');
                document.write('<td><a href="/Home/ViewPdf?id=' + uploadedFiles[i].Id + '" target="_blank">View PDF</a></td>');
                document.write('</tr>');
            }
        </script>
    </table>

    <h2>Upload File</h2>

    <form action="/Home/UploadFile" method="post" enctype="multipart/form-data">
        <label for="Name">Name:</label>
        <input type="text" name="Name" id="Name" required />
        <br />
        <input type="file" name="PdfFile" id="PdfFile" required />
        <input type="submit" value="Upload" />
    </form>
</body>

</html>

Upvotes: 0

Tim
Tim

Reputation: 5859

If anyone finds this by searching for HttpPostedFileBase it's possible you're familiar with writing ASP.NET controller methods something like this:

public async Task<IActionResult> DoThing(MyViewModel model, HttpPostedFileBase fileOne, HttpPostedFileBase fileTwo)
{
   //process files here
}

If you're wanting to write an equivalent in ASP.NET Core then you can write it like this:

public async Task<IActionResult> DoThing(MyViewModel model, IFormFile fileOne, IFormFile fileTwo)
{
   //process files here
}

i.e. the only change needed to the method signature is replacing HttpPostedFileBase with IFormFile. You will then need to modify your method to work with the new parameter type (e.g. HttpPostedFileBase has an InputStream property, whereas IFormFile has a OpenReadStream() method) but I think the details of those differences are beyond the scope of this question.

Upvotes: 13

Kabindas
Kabindas

Reputation: 832

You should also be able to get the files like this :

    [HttpPost]
    public ActionResult UploadFiles()
    {
        var files = Request.Form.Files;
        return Ok();
    }

Upvotes: 8

Chris Pratt
Chris Pratt

Reputation: 239420

HttpPostedFileBase doesn't exist in ASP.NET Core. You should use IFormFile now, instead. However, that only works when you send the request as multipart/form-data, which you're likely not doing if you're working with a client-side framework like React. If you're posting JSON, you should set the JSON member that corresponds with your file property with the file encoded as a Base64 string. Server-side, you should then bind to byte[].

Upvotes: 20

Razvan Dumitru
Razvan Dumitru

Reputation: 12462

You don't have HttpPostedFileBase in ASP.NET Core 2.0, but you can use IFormFile.

[HttpPost("UploadFiles")]
public async Task<IActionResult> Post(List<IFormFile> files)
{
    long size = files.Sum(f => f.Length);

    // full path to file in temp location
    var filePath = Path.GetTempFileName();

    foreach (var formFile in files)
    {
        if (formFile.Length > 0)
        {
            using (var stream = new FileStream(filePath, FileMode.Create))
            {
                await formFile.CopyToAsync(stream);
            }
        }
    }

    // process uploaded files
    // Don't rely on or trust the FileName property without validation.

    return Ok(new { count = files.Count, size, filePath});
}

More here: https://learn.microsoft.com/en-us/aspnet/core/mvc/models/file-uploads?view=aspnetcore-2.1

IFormFile is in the following namespace Microsoft.AspNetCore.Http.

Upvotes: 78

Related Questions