Click here to Skip to main content
15,886,518 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hello,

This code saves files on wwwroot folder.
How to save Id and name and URL in the model? is it possible for a controller to do these tasks?

regards,

What I have tried:

C#
[Route("WeatherForecast/Post")]
        [HttpPost]
        public IActionResult Post([FromForm] FileModel file)
        {
            try
            {
                string path = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", file.FileName);

                using (Stream stream = new FileStream(path, FileMode.Create))
                {

                    file.FormFile.CopyTo(stream);

                }

                return StatusCode(StatusCodes.Status201Created);

            }

            catch (Exception)
            {
                return StatusCode(StatusCodes.Status500InternalServerError);
            }
        }

C#
<pre>
namespace imageEditor3
{

    public class FileContext : DbContext
    {
        public DbSet<FileModel> FileModels { get; set; }
    }
    public class FileModel
    {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int FileId { get; set; }
        public string FileName { get; set; }
        public IFormFile FormFile { get; set; }
    }
}


C#
<pre>import React, { useState } from "react";
import axios from "axios";


export  const FileUpload = () => {

    

        const [file, setFile] = useState();
    const [fileName, setFileName] = useState();
    //const [fileURL, setFileURL] = useState();


        const SaveFile = (e) => {

            console.log(e.target.files[0]);
            setFile(e.target.files[0]);
            setFileName(e.target.files[0].name);
            //setFileURL(e.target.files[0].fileURL);

    };

    const UploadFile = async (e) => {
        console.log(file);
        const formData = new FormData();
        formData.append("formFile", file);
        formData.append("fileName", fileName);

        try {
            const res = await axios.post("WeatherForecast/WeatherForecast/post", formData);
              
            
            console.log(res);

        } catch (ex) {
            console.log(ex);
        }
    };

    return (
        <>
            <input type="file" onChange={SaveFile} />
            <input type="button" value="upload" onClick={UploadFile} />
        </>

        );

    
};
Posted
Updated 17-Jan-21 9:58am
v2
Comments
F-ES Sitecore 17-Jan-21 9:48am    
Do you mean that FileModel has other field in it like ID? If so you can access those properties as normal, so file.ID, and save them wherever you want. If you want to construct a url to the file you've just created you'll probably have to do that yourself by building it from the items like Request.Uri.Authority which will give you the domain then just add the wwroot and filename yourself.
SaeedPol 17-Jan-21 15:55pm    
Yes it has. The model contains:
public int FileId { get; set; }
public string FileName { get; set; }
public IFormFile FormFile { get; set; }

Can you tell me by an example?tnx
Richard Deeming 18-Jan-21 5:22am    
string path = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", file.FileName);

NB: Is it possible for the FileName property to contain a complete file path. Path.Combine would then return that path, which could be outside of your wwwroot directory. This would allow an attacker to overwrite arbitrary files on your server, which would be a pretty serious security vulnerability.

You need to call Path.GetFileName on the FileName property to remove any directory information before combining it with the folder:
string path = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", Path.GetFileName(file.FileName));

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900