使用C#和WebRequest上传图像?

使用C#和WebRequest上传图像?,c#,post,httpwebrequest,webrequest,C#,Post,Httpwebrequest,Webrequest,以下是Python中的工作代码(使用cURL): 以下是我在C#中的内容: 现在,我注意到的是,当我将参数字符串中的API键更改为“239231”或任何数字时,得到的响应是:“无效的API键”。因此我认为某些东西一定工作正常 我放置了正确的API密钥,现在得到了不同的响应:“无效的图像格式。请尝试上载JPEG图像。” 我使用的服务几乎接受每种图像格式,所以我100%确定错误在我发送文件的方式上。有人能解释一下吗 编辑 事实证明,当我上传一张JPG图像时,我得到了那个灰色的盒子。如果我上传一个大的

以下是Python中的工作代码(使用cURL):

以下是我在C#中的内容:

现在,我注意到的是,当我将参数字符串中的API键更改为“239231”或任何数字时,得到的响应是:“无效的API键”。因此我认为某些东西一定工作正常

我放置了正确的API密钥,现在得到了不同的响应:“无效的图像格式。请尝试上载JPEG图像。”

我使用的服务几乎接受每种图像格式,所以我100%确定错误在我发送文件的方式上。有人能解释一下吗

编辑

事实证明,当我上传一张JPG图像时,我得到了那个灰色的盒子。如果我上传一个大的jpg图片,我什么也得不到。例如:

当我上传PNG时,上传的图像甚至不显示

我确信问题在于编码。我能做什么

编辑2

现在我100%确定问题在于方法的第一行。文件.ReadAllBytes()一定是做错了什么。如果我上传一个URL文件,每个文件都会运行良好:

我想知道我应该用什么编码S

尝试更改:-

"application/x-www-form-urlencoded"

试试这个:

string file = @"C:\Users\Sergio\documents\visual studio 2010\Projects\WpfApplication1\WpfApplication1\Test\Avatar.png";
string parameters = @"key=1df918979bf3f8dff2125c22834210903&image=" +
    Convert.ToBase64String(File.ReadAllBytes(file));

尝试将jpg的内容类型添加到多部分边界中

请参见此uRL以获取示例(在末尾)


您应该正确地形成多部分POST请求。请参见此处的示例:

在黑暗中拍摄,但可能会创建一个Image实例,将文件保存到流中,并使用该流将字节读取到数组中,然后上载它

例如:

Image i = System.Drawing.Image.FromFile("wut.jpg");
Stream stm = new Stream();
System.Drawing.Imaging.Encoder myEncoder = System.Drawing.Imaging.Encoder.Quality;
System.Drawing.Imaging.EncoderParameters paramz = new System.Drawing.Imaging.EncoderParameters(1);
myEncoderParameter = new EncoderParameter(myEncoder, 100L);
paramz.Param[0] = myEncoderParameter;
i.Save(stm, System.Drawing.Imaging.ImageFormat.Jpeg, paramz);
/* I'm lazy: code for reading Stream into byte[] here */

读取API中由发布的图像

public IHttpActionResult UpdatePhysicianImage(HttpRequestMessage request)
    {
        try
        {
            var form = HttpContext.Current.Request.Form;
            var model = JsonConvert.DeserializeObject<UserPic>(form["json"].ToString());
            bool istoken = _appdevice.GettokenID(model.DeviceId);
            if (!istoken)
            {
                statuscode = 0;
                message = ErrorMessage.TockenNotvalid;
                goto invalidtoken;
            }
            HttpResponseMessage result = null;
            var httpRequest = HttpContext.Current.Request;
            if (httpRequest.Files.Count > 0)
            {
                var docfiles = new List<string>();
                foreach (string file in httpRequest.Files)
                {
                    var postedFile = httpRequest.Files[file];
                    // var filePath = uploadPath + postedFile.FileName;
                    //  string fileUrl = Utility.AbsolutePath("~/Data/User/" + model.UserId.ToString());
                    string fileUrl = Utility.AbsolutePath("~/" + Utility.UserDataFolder(model.UserId, "Document"));
                    if (!Directory.Exists(fileUrl))
                    {
                        Directory.CreateDirectory(fileUrl);
                        Directory.CreateDirectory(fileUrl + "\\" + "Document");
                        Directory.CreateDirectory(fileUrl + "\\" + "License");
                        Directory.CreateDirectory(fileUrl + "\\" + "Profile");
                    }
                    string imageUrl = postedFile.FileName;
                    string naviPath = Utility.ProfileImagePath(model.UserId, imageUrl);
                    var path = Utility.AbsolutePath("~/" + naviPath);
                    postedFile.SaveAs(path);
                    docfiles.Add(path);
                    if (model.RoleId == 2)
                    {
                        var doctorEntity = _doctorProfile.GetNameVideoChat(model.UserId);
                        doctorEntity.ProfileImagePath = naviPath;
                        _doctorProfile.UpdateDoctorUpdProfile(doctorEntity);
                    }
                    else
                    {
                        var patientEntity = _PatientProfile.GetPatientByUserProfileId(model.UserId);
                        patientEntity.TumbImagePath = naviPath;
                        _PatientProfile.UpdatePatient(patientEntity);
                    }
                }
                result = Request.CreateResponse(HttpStatusCode.Created, docfiles);
            }
            else
            {
                result = Request.CreateResponse(HttpStatusCode.BadRequest);
            }
        }
        catch (Exception e)
        {
            statuscode = 0;
            message = "Error" + e.Message;
        }
    invalidtoken:
        return Json(modeldata.GetData(statuscode, message));
    }
public IHttpActionResult UpdatePhysicianImage(HttpRequestMessage请求)
{
尝试
{
var form=HttpContext.Current.Request.form;
var model=JsonConvert.DeserializeObject(形式为[“json”].ToString());
bool-istoken=\u-appdevice.GettokenID(model.DeviceId);
如果(!istoken)
{
statuscode=0;
message=ErrorMessage.TockenNotvalid;
转到无效代币;
}
HttpResponseMessage结果=null;
var httpRequest=HttpContext.Current.Request;
如果(httpRequest.Files.Count>0)
{
var docfiles=新列表();
foreach(httpRequest.Files中的字符串文件)
{
var postedFile=httpRequest.Files[file];
//var filePath=uploadPath+postedFile.FileName;
//字符串fileUrl=Utility.AbsolutePath(“~/Data/User/”+model.UserId.ToString());
字符串fileUrl=Utility.AbsolutePath(“~/”+Utility.UserDataFolder(model.UserId,“Document”);
如果(!Directory.Exists(fileUrl))
{
CreateDirectory(fileUrl);
CreateDirectory(fileUrl+“\\”+“文档”);
CreateDirectory(fileUrl+“\\”+“许可证”);
CreateDirectory(fileUrl+“\\”+“Profile”);
}
字符串imageUrl=postedFile.FileName;
字符串naviPath=Utility.ProfileImagePath(model.UserId,imageUrl);
var path=Utility.AbsolutePath(“~/”+naviPath);
postedFile.SaveAs(路径);
添加(路径);
如果(model.RoleId==2)
{
var doctorEntity=\u doctorProfile.GetNameVideoChat(model.UserId);
doctorEntity.ProfileImagePath=naviPath;
_doctorProfile.UpdateDoctorUpdProfile(doctorEntity);
}
其他的
{
var patiententy=_PatientProfile.GetPatientByUserProfileId(model.UserId);
patiententy.tumbiagepath=naviPath;
_PatientProfile.UpdatePatient(耐心);
}
}
结果=Request.CreateResponse(HttpStatusCode.Created,docfiles);
}
其他的
{
结果=Request.CreateResponse(HttpStatusCode.BadRequest);
}
}
捕获(例外e)
{
statuscode=0;
message=“Error”+e.消息;
}
invalidtoken:
返回Json(modeldata.GetData(statuscode,message));
}

这在某种程度上起了作用。我想我是在读取完所有字节之前发送文件的,因为我收到了这个图像:也许你应该向API提供商询问,或者你的当前图像已损坏,或者尝试上载JPEG图像我不知道上载出了什么问题。查看此图片:如果您注意到,顶部有一点图片,可能是我关闭连接太早了?我如何检查这个?我得到了一个响应OK,这是预期的响应,它甚至给了我上传图像的链接。我认为问题在于图像的编码SFileInfo fi=新文件信息(路径);字节[]内容=新字节[(int)fi.Length];新文件流(path,FileMode.Open).Read(content,0,content.Length);当代码从Python执行时,尝试使用诸如Fiddler之类的工具查看数据是如何发布的。另外,请参阅从.net完成请求时如何发送请求和数据。这将有助于你发现差异,并在以后解决问题。聪明的人能给出理由吗+1保持平衡。是的,对于像文件这样的大文件,一定要使用多部分。@SergioTapia您实际上必须以多部分的形式发送信息。
string file = @"C:\Users\Sergio\documents\visual studio 2010\Projects\WpfApplication1\WpfApplication1\Test\Avatar.png";
string parameters = @"key=1df918979bf3f8dff2125c22834210903&image=" +
    Convert.ToBase64String(File.ReadAllBytes(file));
Image i = System.Drawing.Image.FromFile("wut.jpg");
Stream stm = new Stream();
System.Drawing.Imaging.Encoder myEncoder = System.Drawing.Imaging.Encoder.Quality;
System.Drawing.Imaging.EncoderParameters paramz = new System.Drawing.Imaging.EncoderParameters(1);
myEncoderParameter = new EncoderParameter(myEncoder, 100L);
paramz.Param[0] = myEncoderParameter;
i.Save(stm, System.Drawing.Imaging.ImageFormat.Jpeg, paramz);
/* I'm lazy: code for reading Stream into byte[] here */
public IHttpActionResult UpdatePhysicianImage(HttpRequestMessage request)
    {
        try
        {
            var form = HttpContext.Current.Request.Form;
            var model = JsonConvert.DeserializeObject<UserPic>(form["json"].ToString());
            bool istoken = _appdevice.GettokenID(model.DeviceId);
            if (!istoken)
            {
                statuscode = 0;
                message = ErrorMessage.TockenNotvalid;
                goto invalidtoken;
            }
            HttpResponseMessage result = null;
            var httpRequest = HttpContext.Current.Request;
            if (httpRequest.Files.Count > 0)
            {
                var docfiles = new List<string>();
                foreach (string file in httpRequest.Files)
                {
                    var postedFile = httpRequest.Files[file];
                    // var filePath = uploadPath + postedFile.FileName;
                    //  string fileUrl = Utility.AbsolutePath("~/Data/User/" + model.UserId.ToString());
                    string fileUrl = Utility.AbsolutePath("~/" + Utility.UserDataFolder(model.UserId, "Document"));
                    if (!Directory.Exists(fileUrl))
                    {
                        Directory.CreateDirectory(fileUrl);
                        Directory.CreateDirectory(fileUrl + "\\" + "Document");
                        Directory.CreateDirectory(fileUrl + "\\" + "License");
                        Directory.CreateDirectory(fileUrl + "\\" + "Profile");
                    }
                    string imageUrl = postedFile.FileName;
                    string naviPath = Utility.ProfileImagePath(model.UserId, imageUrl);
                    var path = Utility.AbsolutePath("~/" + naviPath);
                    postedFile.SaveAs(path);
                    docfiles.Add(path);
                    if (model.RoleId == 2)
                    {
                        var doctorEntity = _doctorProfile.GetNameVideoChat(model.UserId);
                        doctorEntity.ProfileImagePath = naviPath;
                        _doctorProfile.UpdateDoctorUpdProfile(doctorEntity);
                    }
                    else
                    {
                        var patientEntity = _PatientProfile.GetPatientByUserProfileId(model.UserId);
                        patientEntity.TumbImagePath = naviPath;
                        _PatientProfile.UpdatePatient(patientEntity);
                    }
                }
                result = Request.CreateResponse(HttpStatusCode.Created, docfiles);
            }
            else
            {
                result = Request.CreateResponse(HttpStatusCode.BadRequest);
            }
        }
        catch (Exception e)
        {
            statuscode = 0;
            message = "Error" + e.Message;
        }
    invalidtoken:
        return Json(modeldata.GetData(statuscode, message));
    }