@laravel_creative_3103

Как загрузить картинку с фронтенда на сервер, используя ReactJS и ASP .NET Web api?

Имеется код на для загрузки картинки на asp web .api
public async Task<PluginModel> CreatePlugin(PluginModelDtO model)
        {

            var newPlugin = new PluginModel()
            {
                Title = model.Title,
                TitleKZ = model.TitleKZ,
                TitleENG = model.TitleENG,
                ShortInfo = model.ShortInfo,
                ShortInfoKZ = model.ShortInfoKZ,
                NameFile = UploadFile(model.ImageFile),
                ShortInfoENG = model.ShortInfoENG,
           
            };
            await context.pluginModelModels.AddAsync(newPlugin);
            await context.SaveChangesAsync();
            return newPlugin;
        }

public string UploadFile(IFormFile model)
        {
            if (model.Length > 0)
            {
                try
                {
                    if (!Directory.Exists(environment.WebRootPath + "\\Images\\"))
                    {
                        Directory.CreateDirectory(environment.WebRootPath + "\\Images\\");
                    }

                    using (FileStream fileStream = System.IO.File.Create(environment.WebRootPath + "\\Images\\" + 
                                   model.FileName))
                    {
                        model.CopyTo(fileStream);
                        fileStream.Flush();
                        return httpContext.HttpContext.Request.Host.Value.ToString() + "\\Images\\" + model.FileName;
                    }
                }
                catch (Exception ex)
                {

                    return ex.ToString();
                }
            }
            else
            {
                throw new Exception("Upload Files");
            }
        }


Ответ от сервера таков:
63f58814ec8ad181841610.png
63f5881ec8798279763696.png

Также имеется код с фронтенда (Реакт) для картинки на сервер:
Но он мне выдает ошибку: каким образом прописать на фронте код правильно, чтоб загрузился пост с картинкой?
const createNewPlugin = async (e) => {
    e.preventDefault();

    const formData = new FormData();
    formData.append('title', titlePlugin);
    formData.append('titleKZ', titlePluginKZ);
    formData.append('titleENG', titlePluginENG);
    formData.append('shortInfo', shortInfoPlugin);
    formData.append('shortInfoKZ', shortInfoPluginKZ);
    formData.append('shortInfoENG', shortInfoPluginENG);
    formData.append('imageFile', selectedFile);
    formData.append('nameFile', nameFile);
    // const newPlugin = {
    //   title: titlePlugin,
    //   titleKZ: titlePluginKZ,
    //   titleENG: titlePluginENG,
    //   shortInfo: shortInfoPlugin,
    //   shortInfoKZ: shortInfoPluginKZ,
    //   shortInfoENG: shortInfoPluginENG,
    //   nameFile: nameFile,
    // };

    const url = 'https://localhost:7183/createPlugin';

    await fetch(url, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Content-Type': 'multipart/form-data;',
      },
      body: formData,
    })
      .then((response) => response.json())
      .then((result) => console.log(result));

    navigate('/plugins');
  };
return (
    <div className="container">
      <Form onSubmit={createNewPlugin} style={{ marginTop: 100 }}>
        <Form.Group className="mb-3" controlId="exampleForm.ControlInput1">
          <Form.Label>Название плагина</Form.Label>
          <Form.Control
            type="file"
            placeholder="Загрузите картинку"
            readOnly
            onChange={handleChangeImg}
            accept="image/*, .png, .jpg, .gif, .web"
          />
        </Form.Group>
        <hr />
        <Form.Group className="mb-3" controlId="exampleForm.ControlInput1">
          <Form.Label>Название плагина</Form.Label>
          <Form.Control
            type="text"
            placeholder="название плагина..."
            value={titlePlugin}
            onChange={(e) => setTitlePlugin(e.target.value)}
          />
        </Form.Group>
        <Form.Group className="mb-3" controlId="exampleForm.ControlInput1">
          <Form.Label>Название плагина(КАЗАХСКИЙ)</Form.Label>
          <Form.Control
            type="text"
            placeholder="название плагина...((казахский)"
            value={titlePluginKZ}
            onChange={(e) => setTitlePluginKZ(e.target.value)}
          />
        </Form.Group>
        <Form.Group className="mb-3" controlId="exampleForm.ControlInput1">
          <Form.Label>Название плагина(АНГЛИЙСКИЙ)</Form.Label>
          <Form.Control
            type="text"
            placeholder="название плагина...(английский)"
            value={titlePluginENG}
            onChange={(e) => setTitlePluginENG(e.target.value)}
          />
          <hr />
        </Form.Group>
        <Form.Group className="mb-3" controlId="exampleForm.ControlTextarea1">
          <Form.Label>Короткая информация</Form.Label>
          <Form.Control
            as="textarea"
            rows={3}
            value={shortInfoPlugin}
            onChange={(e) => setShortInfoPlugin(e.target.value)}
          />
        </Form.Group>
        <Form.Group className="mb-3" controlId="exampleForm.ControlTextarea1">
          <Form.Label>Короткая информация(КАЗАХСКИЙ)</Form.Label>
          <Form.Control
            as="textarea"
            rows={3}
            value={shortInfoPluginKZ}
            onChange={(e) => setShortInfoPluginKZ(e.target.value)}
          />
        </Form.Group>
        <Form.Group className="mb-3" controlId="exampleForm.ControlTextarea1">
          <Form.Label>Короткая информация(АНГЛИЙСКИЙ)</Form.Label>
          <Form.Control
            as="textarea"
            rows={3}
            value={shortInfoPluginENG}
            onChange={(e) => setShortInfoPluginENG(e.target.value)}
          />
        </Form.Group>
        <Button type="submit" variant="success">
          Создать
        </Button>{' '}
        <Button onClick={() => navigate('/plugins')} variant="secondary">
          Отменить
        </Button>{' '}
      </Form>
    </div>
  );


Ошибка:
63f58881d95be345189612.png
  • Вопрос задан
  • 331 просмотр
Пригласить эксперта
Ответы на вопрос 1
firedragon
@firedragon
Не джун-мидл-сеньор, а трус-балбес-бывалый.
https://github.com/vkorotenko/VueRecaptcha/blob/ma...

var imagefile = document.getElementById("upload_files") as HTMLInputElement;
    if (imagefile == null) return;
    if (imagefile.files == null) return;
    const files = imagefile.files;
    for (let i = 0; i < files.length; i++) {
      formData.append("files", files[i]);
    }
Ответ написан
Комментировать
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы