尝试将 ImageData 发送到我的数据库
Trying to send an ImageData to my database
我正在尝试将图像数据发送到我的数据库,但我不确定应该如何让它工作。这是我当前的代码:
这是我的数据库 csfile,我尝试在其中为我的数据库创建图像(它正在工作,但我不确定是否应该将它作为字节 [] 发送,因为我的数据库需要它作为文件)
static public async Task<bool> createInfo (byte[] thePicture) // should I send it as byte??
我 "create" 将数据发送到我的数据库 csfile 的页面。
myViewModel = new PhotoAlbumViewModel ();
async void button (object sender, EventArgs args)
{
var createResult = await parseAPI.createInfo
(myViewModel.ImageData); //sending my imagedata to my database
}
还有我的 PhotoAlbumViewModel,我在其中创建了包含图像数据字节的图像数据:
private byte[] imageData;
public byte[] ImageData { get { return imageData; } }
private byte[] ReadStream(Stream input)
{
byte[] buffer = new byte[16*1024];
using (MemoryStream ms = new MemoryStream())
{
int read;
while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
{
ms.Write(buffer, 0, read);
}
return ms.ToArray();
}
}
public async Task SelectPicture()
{
Setup ();
ImageSource = null;
try
{
var mediaFile = await _Mediapicker.SelectPhotoAsync(new CameraMediaStorageOptions
{
DefaultCamera = CameraDevice.Front,
MaxPixelDimension = 400
});
VideoInfo = mediaFile.Path;
ImageSource = ImageSource.FromStream(() => mediaFile.Source);
imageData = ReadStream(mediaFile.Source);
}
catch (System.Exception ex)
{
Status = ex.Message;
}
}
已更新数据库 cscode:
static public async Task<bool> createInfo (byte[] thePicture)
{
var httpClientRequest = new HttpClient ();
httpClientRequest.DefaultRequestHeaders.Add ("X-Parse-Application-Id", appId);
httpClientRequest.DefaultRequestHeaders.Add ("X-Parse-REST-API-Key", apiKey);
var postData = new Dictionary <object, object> ();
postData.Add ("image", thePicture);
var jsonRequest = JsonConvert.SerializeObject(postData);
jsonRequest = jsonRequest.Replace ("\"ACLDATA\"", "{\""+userId+"\" : { \"read\": true, \"write\": true }, \"*\" : {}}");
HttpContent content = new StringContent(jsonRequest, System.Text.Encoding.UTF8, "application/json");
var result = await httpClientRequest.PostAsync("https://api.parse.com/1/classes/Info", content);
var resultString = await result.Content.ReadAsStringAsync ();
return true;
}
最后,您遇到的问题是您对 Post API 的调用是错误的。
它需要一个内容为二进制内容的纯 POST 请求,而您正在执行一个 REST 请求。
这段代码可以做到:
public static void SendFile(string FileName, string MimeType, byte[] FileContent, string ClientId, string ApplicationId, string ApiKey, Action<string> OnCompleted)
{
string BaseServer = "https://api.parse.com/{0}/files/{1}";
HttpWebRequest req = HttpWebRequest.CreateHttp(string.Format(BaseServer, ClientId, FileName));
SetHeader(req, "X-Parse-Application-Id", ApplicationId);
SetHeader(req, "X-Parse-REST-API-Key", ApiKey);
req.Method = "POST";
req.ContentType = MimeType;
req.BeginGetRequestStream((iResult) =>
{
var str = req.EndGetRequestStream(iResult);
str.Write(FileContent, 0, FileContent.Length);
req.BeginGetResponse((iiResult) => {
var resp = req.EndGetResponse(iiResult);
string result = "";
using (var sr = new StreamReader(resp.GetResponseStream()))
result = sr.ReadToEnd();
OnCompleted(result);
}, null);
}, null);
}
//Modified from
public static void SetHeader(HttpWebRequest Request, string Header, string Value) {
// Retrieve the property through reflection.
PropertyInfo PropertyInfo = Request.GetType().GetRuntimeProperty(Header.Replace("-", string.Empty));
// Check if the property is available.
if (PropertyInfo != null) {
// Set the value of the header.
PropertyInfo.SetValue(Request, Value, null);
} else {
// Set the value of the header.
Request.Headers[Header] = Value;
}
}
那么你可以这样称呼它:
SendFile("image.jpg", "image/jpg", theByteArray, theClientId, yourAppId, yourApiKey, (result) => {
//do whatever you want with the result from the server
});
注意我没有实现任何异常处理,您应该在 GetResponseStream 周围添加一个 try-catch 以防服务器给出带有错误代码的响应并从生成的 WebException 中获取响应。
我正在尝试将图像数据发送到我的数据库,但我不确定应该如何让它工作。这是我当前的代码:
这是我的数据库 csfile,我尝试在其中为我的数据库创建图像(它正在工作,但我不确定是否应该将它作为字节 [] 发送,因为我的数据库需要它作为文件)
static public async Task<bool> createInfo (byte[] thePicture) // should I send it as byte??
我 "create" 将数据发送到我的数据库 csfile 的页面。
myViewModel = new PhotoAlbumViewModel ();
async void button (object sender, EventArgs args)
{
var createResult = await parseAPI.createInfo
(myViewModel.ImageData); //sending my imagedata to my database
}
还有我的 PhotoAlbumViewModel,我在其中创建了包含图像数据字节的图像数据:
private byte[] imageData;
public byte[] ImageData { get { return imageData; } }
private byte[] ReadStream(Stream input)
{
byte[] buffer = new byte[16*1024];
using (MemoryStream ms = new MemoryStream())
{
int read;
while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
{
ms.Write(buffer, 0, read);
}
return ms.ToArray();
}
}
public async Task SelectPicture()
{
Setup ();
ImageSource = null;
try
{
var mediaFile = await _Mediapicker.SelectPhotoAsync(new CameraMediaStorageOptions
{
DefaultCamera = CameraDevice.Front,
MaxPixelDimension = 400
});
VideoInfo = mediaFile.Path;
ImageSource = ImageSource.FromStream(() => mediaFile.Source);
imageData = ReadStream(mediaFile.Source);
}
catch (System.Exception ex)
{
Status = ex.Message;
}
}
已更新数据库 cscode:
static public async Task<bool> createInfo (byte[] thePicture)
{
var httpClientRequest = new HttpClient ();
httpClientRequest.DefaultRequestHeaders.Add ("X-Parse-Application-Id", appId);
httpClientRequest.DefaultRequestHeaders.Add ("X-Parse-REST-API-Key", apiKey);
var postData = new Dictionary <object, object> ();
postData.Add ("image", thePicture);
var jsonRequest = JsonConvert.SerializeObject(postData);
jsonRequest = jsonRequest.Replace ("\"ACLDATA\"", "{\""+userId+"\" : { \"read\": true, \"write\": true }, \"*\" : {}}");
HttpContent content = new StringContent(jsonRequest, System.Text.Encoding.UTF8, "application/json");
var result = await httpClientRequest.PostAsync("https://api.parse.com/1/classes/Info", content);
var resultString = await result.Content.ReadAsStringAsync ();
return true;
}
最后,您遇到的问题是您对 Post API 的调用是错误的。
它需要一个内容为二进制内容的纯 POST 请求,而您正在执行一个 REST 请求。
这段代码可以做到:
public static void SendFile(string FileName, string MimeType, byte[] FileContent, string ClientId, string ApplicationId, string ApiKey, Action<string> OnCompleted)
{
string BaseServer = "https://api.parse.com/{0}/files/{1}";
HttpWebRequest req = HttpWebRequest.CreateHttp(string.Format(BaseServer, ClientId, FileName));
SetHeader(req, "X-Parse-Application-Id", ApplicationId);
SetHeader(req, "X-Parse-REST-API-Key", ApiKey);
req.Method = "POST";
req.ContentType = MimeType;
req.BeginGetRequestStream((iResult) =>
{
var str = req.EndGetRequestStream(iResult);
str.Write(FileContent, 0, FileContent.Length);
req.BeginGetResponse((iiResult) => {
var resp = req.EndGetResponse(iiResult);
string result = "";
using (var sr = new StreamReader(resp.GetResponseStream()))
result = sr.ReadToEnd();
OnCompleted(result);
}, null);
}, null);
}
//Modified from
public static void SetHeader(HttpWebRequest Request, string Header, string Value) {
// Retrieve the property through reflection.
PropertyInfo PropertyInfo = Request.GetType().GetRuntimeProperty(Header.Replace("-", string.Empty));
// Check if the property is available.
if (PropertyInfo != null) {
// Set the value of the header.
PropertyInfo.SetValue(Request, Value, null);
} else {
// Set the value of the header.
Request.Headers[Header] = Value;
}
}
那么你可以这样称呼它:
SendFile("image.jpg", "image/jpg", theByteArray, theClientId, yourAppId, yourApiKey, (result) => {
//do whatever you want with the result from the server
});
注意我没有实现任何异常处理,您应该在 GetResponseStream 周围添加一个 try-catch 以防服务器给出带有错误代码的响应并从生成的 WebException 中获取响应。