C# 上载UIImage(Xamarin)类型的图像列表
我的应用程序将从特定文件夹中检索所有图像的列表,并尝试通过API端点将它们上载到服务器 由于上述要求,不适合使用图像选择器 下面是共享代码中的方法,它被传递了一个UIImages列表(我现在正试图让它只在ios上工作,但同样的场景最终也将应用到Android上) 下面的内容不起作用,因为当我在服务器(AWS)上查看图像时,它是代码格式的。它还说服务器上的内容类型是application/json,我不理解,因为我正在将其设置为image/pngC# 上载UIImage(Xamarin)类型的图像列表,c#,xamarin.forms,uiimage,dotnet-httpclient,C#,Xamarin.forms,Uiimage,Dotnet Httpclient,我的应用程序将从特定文件夹中检索所有图像的列表,并尝试通过API端点将它们上载到服务器 由于上述要求,不适合使用图像选择器 下面是共享代码中的方法,它被传递了一个UIImages列表(我现在正试图让它只在ios上工作,但同样的场景最终也将应用到Android上) 下面的内容不起作用,因为当我在服务器(AWS)上查看图像时,它是代码格式的。它还说服务器上的内容类型是application/json,我不理解,因为我正在将其设置为image/png private async Task Upload
private async Task UploadImages(List<UIImage> images)
{
HttpClient client = new HttpClient();
var contentType = new MediaTypeWithQualityHeaderValue("image/png");
client.DefaultRequestHeaders.Accept.Add(contentType);
client.DefaultRequestHeaders.Add("Id-Token", Application.Current.Properties["id_token"].ToString());
foreach (var image in images)
{
try
{
string baseUrl = $"https://********/dev/ferret-test/media/team1/user1/device1/test1.png";
client.BaseAddress = new Uri(baseUrl);
//UploadModel uploadModel = new UploadModel
//{
// image_file = image.AsPNG()
//};
byte[] bArray = null;
Stream pst = image.AsPNG().AsStream();
using (MemoryStream ms = new MemoryStream())
{
ms.Position = 0;
pst.CopyTo(ms);
bArray = ms.ToArray();
}
//string stringData = JsonConvert.SerializeObject(bArray);
//var contentData = new StringContent(stringData,
//System.Text.Encoding.UTF8, "image/png");
//Byte[] myByteArray = new Byte[imageData.Length];
//System.Runtime.InteropServices.Marshal.Copy(imageData.Bytes, myByteArray, 0, Convert.ToInt32(imageData.Length));
var postRequest = new HttpRequestMessage(HttpMethod.Put, baseUrl)
{
Content = new ByteArrayContent(bArray)
};
var response = await client.SendAsync(postRequest);
response.EnsureSuccessStatusCode();
string stringJWT = response.Content.ReadAsStringAsync().Result;
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
}
私有异步任务上载映像(列表映像)
{
HttpClient=新的HttpClient();
var contentType=新的MediaTypeWithQualityHeaderValue(“图像/png”);
client.DefaultRequestHeaders.Accept.Add(contentType);
client.DefaultRequestHeaders.Add(“Id Token”,Application.Current.Properties[“Id_Token”].ToString());
foreach(图像中的var图像)
{
尝试
{
string baseUrl=$“https://*********/dev/ferret test/media/team1/user1/device1/test1.png”;
client.BaseAddress=新Uri(baseUrl);
//UploadModel UploadModel=新的UploadModel
//{
//image\u file=image.AsPNG()
//};
字节[]bArray=null;
Stream pst=image.AsPNG().AsStream();
使用(MemoryStream ms=new MemoryStream())
{
ms.Position=0;
pst.CopyTo(ms);
bArray=ToArray女士();
}
//string stringData=JsonConvert.SerializeObject(bArray);
//var contentData=新的StringContent(stringData,
//System.Text.Encoding.UTF8,“图像/png”);
//字节[]myByteArray=新字节[imageData.Length];
//System.Runtime.InteropServices.Marshal.Copy(imageData.Bytes,myByteArray,0,Convert.ToInt32(imageData.Length));
var postRequest=新的HttpRequestMessage(HttpMethod.Put,baseUrl)
{
内容=新的ByteArrayContent(bArray)
};
var response=await client.sendsync(postRequest);
response.EnsureSuccessStatusCode();
字符串stringJWT=response.Content.ReadAsStringAsync().Result;
}
捕获(例外情况除外)
{
控制台写入线(ex);
}
}
}
您可以尝试使用MultipartFormDataContent
并将内容类型设置为application/octet-stream
您可以参考这两个链接和。我使用以下代码段将多个文件上传到服务器,您可以尝试一下
foreach (SQLiteAccess.Tables.Image image in images.OrderByDescending(x => x.Id)) //Here is the collection of all the file at once (Documents + Images)
{
int documentId = UploadImageToServerAndroid(image).Result;
// My other code implementation
.
.
.
}
private async Task<int> UploadImageToServerAndroid(SQLiteAccess.Tables.Image image)
{
int documentId = 0;
if (!Admins.ConnectedToNetwork()) return documentId;
MyFile = FileSystem.Current.GetFileFromPathAsync(image.Path).Result;
if (MyFile == null) return documentId;
Stream stream = MyFile.OpenAsync(FileAccess.Read).Result;
byte[] byteArray;
byteArray = new byte[stream.Length];
stream.Read(byteArray, 0, (int)stream.Length);
if( !image.IsDocument )
{
try
{
byteArray = DependencyService.Get<IImageUtilities>().CompressImage(byteArray); //Its custom code to compress the Image.
}
catch (Exception ex)
{
UoW.Logs.LogMessage(new LogDTO { Message = ex.Message, Ex = ex });
}
}
string url = "Your URL";
using (HttpClient client = new HttpClient(new RetryMessageHandler(new HttpClientHandler())))
{
try
{
client.DefaultRequestHeaders.Add(Properties.Resources.Authorization, Sessions.BearerToken);
client.DefaultRequestHeaders.Add("DocumentSummary", image.Comment);
client.DefaultRequestHeaders.Add("DocumentName", Path.GetFileName(image.Path));
MultipartFormDataContent multiPartContent = new MultipartFormDataContent();
ByteArrayContent byteContent = new ByteArrayContent(byteArray);
byteContent.Headers.ContentType = MediaTypeHeaderValue.Parse("image/jpeg");
multiPartContent.Add(byteContent, "image", Path.GetFileName(image.Path));
HttpResponseMessage response = await client.PostAsync(url, multiPartContent);
if (response.IsSuccessStatusCode && response.Content != null)
{
string jsonString = response.Content.ReadAsStringAsync().Result;
DocumentDTO result = JsonConvert.DeserializeObject<DocumentDTO>(jsonString);
documentId = result.DocumentId;
}
}
catch(Exception ex)
{
UoW.Logs.LogMessage( new LogDTO { Message = ex.Message, Ex = ex });
return documentId;
}
}
return documentId;
}
foreach(images.OrderByDescending(x=>x.Id))中的SQLiteAccess.Tables.Image图像//这里是所有文件(文档+图像)的集合
{
int documentId=UploadImageToServerAndroid(图像).Result;
//我的另一个代码实现
.
.
.
}
私有异步任务上载ImageToServerAndroid(SQLiteAccess.Tables.Image)
{
int documentId=0;
如果(!Admins.connectedtonework())返回documentId;
MyFile=FileSystem.Current.GetFileFromPathAsync(image.Path).Result;
如果(MyFile==null)返回documentId;
Stream=MyFile.OpenAsync(FileAccess.Read).Result;
字节[]字节数组;
byteArray=新字节[stream.Length];
读取(字节数组,0,(int)stream.Length);
如果(!image.IsDocument)
{
尝试
{
byteArray=DependencyService.Get().CompressImage(byteArray);//压缩图像的自定义代码。
}
捕获(例外情况除外)
{
LogMessage(新LogDTO{Message=ex.Message,ex=ex});
}
}
string url=“您的url”;
使用(HttpClient client=new-HttpClient(new-RetryMessageHandler(new-HttpClientHandler()))
{
尝试
{
client.DefaultRequestHeaders.Add(Properties.Resources.Authorization,Sessions.BearerToken);
client.DefaultRequestHeaders.Add(“DocumentSummary”,image.Comment);
Add(“DocumentName”,Path.GetFileName(image.Path));
MultipartFormDataContent multiPartContent=新的MultipartFormDataContent();
byteArray内容byteContent=新的byteArray内容(byteArray);
byteContent.Headers.ContentType=MediaTypeHeaderValue.Parse(“图像/jpeg”);
Add(字节内容,“image”,Path.GetFileName(image.Path));
HttpResponseMessage response=wait client.PostAsync(url,multiPartContent);
if(response.issucessstatuscode&&response.Content!=null)
{
字符串jsonString=response.Content.ReadAsStringAsync().Result;
DocumentdToResult=JsonConvert.DeserializeObject(jsonString);
documentId=result.documentId;
}
}
捕获(例外情况除外)
{
LogMessage(新LogDTO{Message=ex.Message,ex=ex});
返回documentId;
}
}
返回documentId;
}
如果documentid为0(如果出于任何原因出现问题),则会将其标记为未上载&当internet可用时,将再次尝试上载它
如果你需要更多的帮助,你可以问…:)现在可以用了吗?