0

我正在用 C# 开发一个连接到 Appcelerator 云服务的应用程序,到目前为止,我可以进行查询并创建自定义对象,现在问题是当我尝试在 ACS 中创建照片时。我查看了这个链接并修改了我的代码,如下所示:

Image img = pbPhoto.Image;
img.Save(Application.StartupPath + "\\tmp.jpg", System.Drawing.Imaging.ImageFormat.Jpeg); //saving the image temporally in hard drive

url = "https://api.cloud.appcelerator.com/v1/photos/create.json?key=appkey&_session_id=" + session;
HttpWebRequest wrGetUrl = (HttpWebRequest)WebRequest.Create(url);

String boundary = "B0unD-Ary";
wrGetUrl.ContentType = "multipart/form-data; boundary=" + boundary;
wrGetUrl.Method = "POST";

String postData = "--" + boundary + "\nContent-Disposition: form-data\n\n";;
postData += "\n--" + boundary + "\nContent-Disposition: form-data; name=\"file\" filename=\"" + Application.StartupPath + "\\tmp.jpg" + "\"\nContent-Type: image/jpeg\n\n";
byteArray = Encoding.UTF8.GetBytes(postData);

byte[] filedata = null;
using (BinaryReader readerr = new BinaryReader(File.OpenRead(Application.StartupPath + "\\tmp.jpg")))
    filedata = readerr.ReadBytes((int)readerr.BaseStream.Length);

wrGetUrl.ContentLength = byteArray.Length + filedata.Length;
wrGetUrl.GetRequestStream().Write(byteArray, 0, byteArray.Length);
wrGetUrl.GetRequestStream().Write(filedata, 0, filedata.Length);

objStream = wrGetUrl.GetResponse().GetResponseStream();
reader = new StreamReader(objStream);

我试过了,但出现以下错误

远程服务器返回错误:(500) 内部服务器错误。

我检查了我的 ACS 日志,但请求没有出现(猜是因为它是 500 错误)。我应该在我的代码中更改什么以上传照片并在 ACS 中创建照片?感谢您提供的任何帮助。

4

1 回答 1

1

找到了这个问题的解决方案:

byte[] filedata = null;
using (BinaryReader readerr = new BinaryReader(File.OpenRead(pathToImage)))
    filedata = readerr.ReadBytes((int)readerr.BaseStream.Length);
string boundary = "-_1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
Stream stream = request.GetRequestStream();
request.ContentType = string.Format("multipart/form-data; boundary={0}", boundary);
StreamWriter writer = new StreamWriter(stream);   
writer.Write("--");
writer.WriteLine(boundary);
writer.WriteLine(@"Content-Disposition: form-data; name=""{0}""; filename=""{1}""", "your_name", "your_photo_file_name");
writer.WriteLine(@"Content-Type: application/octet-stream");
writer.WriteLine(@"Content-Length: " + filedata .Length);
writer.WriteLine();
writer.Flush();
Stream output = writer.BaseStream;
output.Write(filedata , 0, filedata .Length);
output.Flush();
writer.WriteLine();
writer.Write("--");
writer.Write(boundary);
writer.WriteLine("--");
writer.Flush();

编辑:我改变了将标头写入RequestStream的方式,我编写它的方式不是将图片发送到Appcelerator云服务的正确方式,通过curl发送请求并检查我能够登录的ACS想出正确的标题。

希望这可以帮助任何有类似问题的人。

于 2012-08-30T20:00:08.123 回答