我想根据游戏要求在我的网络服务器上传个人资料照片。 为了从设备中选择照片,我使用了这个插件: Native Gallery for Android & iOS
我已使用此代码在网络服务器上传照片,但目前我可以在图片视图组件中加载照片,但无法在网络服务器上传。
IEnumerator PickImage (int maxSize)
{
Texture2D texture = null;
NativeGallery.Permission permission = NativeGallery.GetImageFromGallery (( path) => {
Debug.Log ("Image path: " + path);
if (path != null) {
// Create Texture from selected image
texture = NativeGallery.LoadImageAtPath (path, maxSize);
if (texture == null) {
Debug.Log ("Couldn't load texture from " + path);
return;
}
profileImage.sprite = Sprite.Create (texture, new Rect (0f, 0f, texture.width, texture.height), new Vector2 (0.5f, 0.5f), 100f);
}
}, "Select an image", "image/*", maxSize);
if (texture != null) {
// make texture read and write able
Texture2D readableTexture = DuplicateTexture(texture);
Debug.Log ("readable texture width: " + readableTexture.width + " height: " + readableTexture.height);
WWWForm form = new WWWForm ();
Debug.Log ("player id: " + DataCollection.localPlayer.PlayerId);
form.AddField (GameConstants.ARG_UPLOAD_PHOTO_PLAYER_ID, DataCollection.localPlayer.PlayerId);
form.AddBinaryData (GameConstants.ARG_UPLOAD_PHOTO, readableTexture.GetRawTextureData (), "profilepic.jpg", "image/*");
Dictionary<string,string> headerDisc = form.headers;
WWW www = new WWW (GameConstants.API_UPLOAD_PHOTO, form.data, headerDisc);
yield return www;
if (www.error == null) {
Debug.Log ("Data: " + www.text);
profileImage.sprite = Sprite.Create (texture, new Rect (0f, 0f, texture.width, texture.height), new Vector2 (0.5f, 0.5f), 100f);
} else {
Debug.Log ("Error: " + www.error);
}
}
Debug.Log ("Permission result: " + permission);
}
这是我得到的调试输出:
有一些错误在运行,我无法理解,所以请给我一些帮助。
修改 按钮单击事件代码,此处我已将图像大小缩小为与Web服务器兼容的设置:
public void OnChangePhotoButtonClick ()
{
// Don't attempt to pick media from Gallery/Photos if
// another media pick operation is already in progress
if (NativeGallery.IsMediaPickerBusy ())
return;
// Pick a PNG image from Gallery/Photos
// If the selected image's width and/or height is greater than 512px, down-scale the image
StartCoroutine (PickImage (256));
}
如果我使用RestClient或PostMan,那么该图像会正确上传。
以下是用于获取图像的服务器端代码: