Click here to Skip to main content
15,440,884 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello,

Why I can't upload an image to wwwroot folder?

Is the usage of Axios correct in my code? I used the react/asp core template. when I run the program it shows the page and can choose an image and press the upload button. But nothing happens.

What I have tried:

JavaScript
<pre>import React, { useState } from "react";
import axios from "axios";
//import React, { Component } from 'react
//import React, { Component } from 'react';

export  const FileUpload = () => {

    

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

        const SaveFile = (e) => {

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

    };

    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("https://localhost:44323/api/file", FormData);
            console.log(res);

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

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

        );

    
};

C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;

namespace imageEditor3
{
    public class FileModel
    {
        public string FileName { get; set; }
        public IFormFile FormFile { get; set; }
    }
}

<pre>namespace imageEditor3.Controllers
{
    using Microsoft.AspNetCore.Http;
    using Microsoft.AspNetCore.Mvc;
    using System;
    using System.IO;

    /// <summary>
    /// Defines the <see cref="FileController" />.
    /// </summary>
    [Route("api/file")]
    [ApiController]
    public class FileController : Controller
    {
        /// <summary>
        /// The Post.
        /// </summary>
        /// <param name="file">The file<see cref="FileModel"/>.</param>
        /// <returns>The <see cref="IActionResult"/>.</returns>
        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);
            }
        }
    }
}
Posted
Updated 8-Jan-21 20:15pm

Quote:
Why I can't upload an image to wwwroot folder?
First of all, why would you want to have a web browser upload files to your wwwroot folder? That is one of the highest security loopholes that I can think of.
Quote:
But nothing happens.
Maybe, try to put a breakpoint and see what is sent in the request to your ASP.NET Core server.
 
Share this answer
 
I made a folder and named it images:

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


export  const FileUpload = () => {

    

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

        const SaveFile = (e) => {

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

    };

    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/post", FormData);
              
            
            console.log(res);

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

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

        );

    
};



C#
<pre>using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;

namespace imageEditor3.Controllers
{
    [Route("WeatherForecast")]

    [ApiController]

    public class WeatherForecastController : ControllerBase
    {
        private static readonly string[] Summaries = new[]
        {
            "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
        };

        private readonly ILogger<WeatherForecastController> _logger;

        public WeatherForecastController(ILogger<WeatherForecastController> logger)
        {
            _logger = logger;
        }
        [Route("WeatherForecast/post")]
        [HttpPost]
        public IActionResult Post([FromForm] FileModel file)
        {
            try
            {
                string path = Path.Combine(Directory.GetCurrentDirectory(), "images", file.FileName);

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

                    file.FormFile.CopyTo(stream);

                }

                return StatusCode(StatusCodes.Status201Created);

            }

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



        [HttpGet]
        public IEnumerable<WeatherForecast> Get()
        {
            var rng = new Random();
            return Enumerable.Range(1, 5).Select(index => new WeatherForecast
            {
                Date = DateTime.Now.AddDays(index),
                TemperatureC = rng.Next(-20, 55),
                Summary = Summaries[rng.Next(Summaries.Length)]
            })
            .ToArray();
        }
    }
}
 
Share this answer
 

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