【发布时间】:2020-04-23 08:01:14
【问题描述】:
我是http相关的新手,所以我有点堆积。
我想要的很简单,我需要 POST,将图像上传到这样的服务器:
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
}}
你能帮我看看我做错了什么吗? 谢谢。
【问题讨论】:
-
那么您确定您发布到 imageGallery 服务器的请求确实有效吗?如果不是,它不会抛出异常,您只会在结果中收到错误状态代码。此外,您总是返回结果,这只是一个空字符串。如果你想从你的 POST 请求中返回结果,你应该返回你调用的变量 res
-
可以添加抛出的异常和前端代码吗?它可能是控制器缺少的绑定属性
-
嗯,如果您查看 chrome 开发控制台,UpdateGalleryResources 请求的响应正文是什么?
-
好的,你得到一个 404,这通常意味着你发送请求的 URL 不存在。当我尝试访问 hello.uk 的网站时,它似乎实际上已经关闭,所以我不确定这是否是问题所在?
-
哦,那是有道理的。但我认为这实际上可能是你做错了。如果您将 POST 请求发送到要保存图像的 url,那么该 url 自然还不存在。所以我猜你必须将请求发送到服务器上的其他端点并在请求正文中指定你想要的文件名,但我不知道你正在使用的服务,所以很遗憾我不知道他们的 API 是如何构建的
标签: c# http file-upload dotnet-httpclient