簡體   English   中英

使用 HttpClient 將圖像上傳到 URI

[英]Upload Image to URI using HttpClient

我是關於 http 相關事情的新手,所以我有點堆積。

我想要的很簡單,我需要發布,將圖像上傳到這樣的服務器: http://web.com/imageGalerry

我認為它並不太復雜,但我不知道為什么我沒有收到錯誤,到目前為止,我不確定如何繼續(因為實際上圖片沒有上傳),這是我的代碼:

public async Task<object> UpdateGalleryResources(IFormFile file, int idResouce)
        {
            byte[] data;
            string result = "";
            ByteArrayContent bytes;
            var urlToPost = "http://hello.uk/imagegallery/resources/" + 00+ "/" + file.FileName;

            MultipartFormDataContent multiForm = new MultipartFormDataContent();

            try
            {
                using (var client = new HttpClient())
                {
                    using (var br = new BinaryReader(file.OpenReadStream()))
                    {
                        data = br.ReadBytes((int)file.OpenReadStream().Length);
                    }

                    bytes = new ByteArrayContent(data);
                    multiForm.Add(bytes, "file", file.FileName);
                    //multiForm.Add(new StringContent("value1"), "key1");
                    //multiForm.Add(new StringContent("value2"), "key2");


                    var res = await client.PostAsync(urlToPost, multiForm);
                    return res;
                }
            }
            catch (Exception e)
            {
                throw new Exception(e.ToString());
            }
        }

這是視圖:

<form action="/Galley/UpdateGallery"  method="post" class="dropzone" id="myDropzone">

    <input type="hidden" value="1" name="idResource" />

</form>

以及我用來處理視圖的 dropzone js:

document.addEventListener("DOMContentLoaded", function () {

    // access Dropzone here
    //dropzone.js detecta la version 'camelized' cuando el div tiene la clase dropzone
    Dropzone.options.myDropzone = {
        addRemoveLinks: true,
        //autoProcessQueue: false,
.....
       }

這是我從return res得到的錯誤代碼

  {StatusCode: 404, ReasonPhrase: 'Not Found', Version: 1.1, Content: System.Net.Http.HttpConnection+HttpConnectionResponseContent, Headers:
{
  Server: Microsoft-IIS/8.5
  X-Powered-By: ASP.NET
  Date: Thu, 23 Apr 2020 08:22:52 GMT
  Content-Type: text/html
  Content-Length: 1282
}}

這是我在調試模式下檢查的,我認為一切正常: 在此處輸入圖像描述

你能幫我看看我做錯了什么嗎? 謝謝你。

過去,在將圖像作為 IFormFile 上傳到 ASP.Net controller 時,我發現以下兩段代碼很重要

在視圖中的表單標簽上添加 enctype 屬性

<form enctype="multipart/form-data" othertags="..."></form>

有關 multipart/form-data 含義的解釋: enctype='multipart/form-data' 是什么意思?

然后將正確的綁定添加到您的 controller 參數

public async Task<object> UpdateGalleryResources([FromForm]IFormFile file, int idResouce)

我不確定這將如何與 dropzone 一起使用,但如果 IFormFile 在 controller 中顯示為 null 這可能值得一試

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM