I'm working with android and try to create an app that able to upload several image to the server. I had tried to upload the image to my localhost using xampp, it works well. But when I try to upload to my enterprise server I can't find my file, in the other word. The file can't be written. I don't know what make it failed? This is my code
Upload tp XAMPP
Connection string private static final String url_photo = "http://192.168.7.110/blabla/base.php";
Path static final String path = "C:\\xampp\\htdocs\\psn_asset_oracle\\Images\\";
Upload to actual enterprise server
Connection String private static final String url_photo = "http://192.168.4.27/oracle/logam/am/data_images/android_image/base.php";
Path static final String path = "http://192.168.4.27/oracle/logam/am/data_images/android_image/";
My code to upload to server
params_p.add(new BasicNameValuePair("image_name_1",
image_name_1));
params_p.add(new BasicNameValuePair("image_name_2",
image_name_2));
params_p.add(new BasicNameValuePair("image_name_3",
image_name_3));
params_p.add(new BasicNameValuePair("image_name_4",
image_name_4));
json_photo = jsonParser.makeHttpRequest(url_photo, "POST", params_p);
ArrayList<NameValuePair> params_p = new ArrayList<NameValuePair>();
PHP code
if(isset($_POST["image_name_1"]) && isset($_POST["image_name_2"]) && isset($_POST["image_name_3"]) && isset($_POST["image_name_4"])
&& isset($_POST["image_1"]) && isset($_POST["image_2"]) && isset($_POST["image_3"]) && isset($_POST["image_4"]))
{
$image_name_1 = $_POST["image_name_1"];
$image_name_2 = $_POST["image_name_2"];
$image_name_3 = $_POST["image_name_3"];
$image_name_4 = $_POST["image_name_4"];
$image_1 = $_POST["image_1"];
$image_2 = $_POST["image_2"];
$image_3 = $_POST["image_3"];
$image_4 = $_POST["image_4"];
/*---------base64 decoding utf-8 string-----------*/
$binary_1=base64_decode($image_1);
$binary_2=base64_decode($image_2);
$binary_3=base64_decode($image_3);
$binary_4=base64_decode($image_4);
/*-----------set binary, utf-8 bytes----------*/
header('Content-Type: bitmap; charset=utf-8');
/*---------------open specified directory and put image on it------------------*/
$file_1 = fopen($image_name_1, 'wb');
$file_2 = fopen($image_name_2, 'wb');
$file_3 = fopen($image_name_3, 'wb');
$file_4 = fopen($image_name_4, 'wb');
/*---------------------assign image to file system-----------------------------*/
fwrite($file_1, $binary_1);
fclose($file_1);
fwrite($file_2, $binary_2);
fclose($file_2);
fwrite($file_3, $binary_3);
fclose($file_3);
fwrite($file_4, $binary_4);
fclose($file_4);
$response["message"] = "Success";
echo json_encode($response);
}
I've contact my DBA and asked to give me permission to write the file, and it still doesn't work. The error is json doesn't give "Success" as message that indicate the file failed to be written. I will appreciate any help. Thank you.
Does the file server allows write access permission? Sample of chmod, http://catcode.com/teachmod/
Is your enterprise server online? The IP address looks private to me, 192.168.4.27.
Dont use json use http post.
See below code
HttpClient client = new DefaultHttpClient();
String postURL = "your url";
HttpPost post = new HttpPost(postURL);
try {
MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
ByteArrayBody bab = new ByteArrayBody(img, "image.jpg");
reqEntity.addPart("image", bab);
post.setEntity(reqEntity);
HttpResponse response = client.execute(post);
Here img is your image in ByteArray format
The problem solved after my DBA give me another file path.
Related
I'm having a hard time parsing text together with an image. I'm using the slim rest API, and here's my code:
$app->post('/updateprofile', function () use ($app) {
$json = $app->request->getBody();
$data = json_decode($json, true);
$id = $data["id"];
$influencer_id = $data["influencer_id"];
$first_name = $data["first_name"];
My problem is what if I want to include a file that is being uploaded by user in the client side, which is an android device, how can I parse the image and put it in a variable?
If possible, you should use multipart/form-data for submission instead of json encoded data, so you can access $_FILES directly. If not possible, or you want to keep using json, you could send the image encoded in base64 as a part of your json and decode it on receive like this:
function base64ToImg($base64_string, $filename) {
$f = fopen($filename, "wb");
$data = explode(',', $base64_string);
fwrite($f, base64_decode($data[1]));
fclose($f);
return $filename;
}
base64ToImg($data["image"], "path/to/img");
EDIT
The usual way to send files to a server is to set the enctype="multipart/form-data" in an html form; doing so, your form will look like
<form name = 'formName' enctype="multipart/form-data">
<input name = 'data1' type = 'text'>
<input name = 'file1' type = 'file'>
</form>
In your server, you will receive the info in $_FILES and $_POST:
<?php
$data1 = $_POST["data1"];
$file = $_FILES["file1"];
move_uploaded_file($file["tmp_name"], "path/to/img");
?>
Since you said that it was an android device, I will add that the form stuff may not be of help if what you are developing is an android app you will have to do something like this (more or less, it has been a long long time since my last android app).
httpClient = new DefaultHttpClient();
post = new HttpPost(yourUrl);
post.setHeader("Content-type", "multipart/form-data");
MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
multipartEntity.addPart("data1", new StringBody(data1));
multipartEntity.addPart("file1", new FileBody(file1));
post.setEntity(multipartEntity);
response = httpClient.execute(httpPost);
I am trying to send compress string message by android device to PHP server.
This is my android code
ByteArrayOutputStream os = new ByteArrayOutputStream(string.length());
GZIPOutputStream gos = new GZIPOutputStream(os);
gos.write(string.getBytes());
gos.close();
byte[] compressed = os.toByteArray();
os.close();
and this is my php code to decode
$msg=$_GET['MsgType'];
$msg2=urldecode($msg);
print gzuncompress($msg2);
but there is error
Message: gzuncompress(): data error
i searched alot on google but didn't help if any one could help me most welcome.
You should use a post variable because url's lenght is limited to few KBs...!
You should use the following code to compress the String
public static String compressAndSend(String str, String url) throws IOException {
String body1 = str;
URL url1 = new URL(url);
URLConnection conn1 = url1.openConnection();
conn1.setDoOutput(true);
conn1.setRequestProperty("Content-encoding", "gzip");
conn1.setRequestProperty("Content-type", "application/octet-stream");
GZIPOutputStream dos1 = new GZIPOutputStream(conn1.getOutputStream());
dos1.write(body1.getBytes());
dos1.flush();
dos1.close();
BufferedReader in1 = new BufferedReader(new InputStreamReader(
conn1.getInputStream()));
String decodedString1 = "";
while ((decodedString1 = in1.readLine()) != null) {
Log.e("dump",decodedString1);
}
in1.close();
}
On PHP side use this,
<?php echo substr($HTTP_RAW_POST_DATA,10,-8); ?>
And please concern this Help manual for more information,
http://php.net/manual/en/function.gzuncompress.php
I have bitmao instance i convert this instance into base64string and send it to server over php function. Now i am decoding this string and calling imagecreatefromstring but this function is giving 500 internal server error. I want this image to be store into file.
My .net function is as follows:
Bitmap icon = new Bitmap("C:\\Users\\HP\\Desktop\\mun.ico");
System.IO.MemoryStream stream = new System.IO.MemoryStream();
icon.Save(stream, System.Drawing.Imaging.ImageFormat.Bmp);
byte[] imageBytes = stream.ToArray();
// Convert byte[] to Base64 String
string base64String = Convert.ToBase64String(imageBytes);
HttpWebRequest m_ObjRequest; //Request which needed to be sent to server
HttpWebResponse m_ObjResponse; // Response which is sent back from the server to the client
StreamReader reader = null; // making a stream reader to read the web pageand initialize it to null
string m_Url = "http://192.168.1.30/muneem/erp/uploadIcon.php"+ "?bitmap=" + base64String; // the url of that web page
string m_Response = "";
m_ObjRequest = (HttpWebRequest)WebRequest.Create(m_Url); // creating the url and setting the values
m_ObjRequest.Method = "GET";
m_ObjRequest.ContentType = "application/json; charset=utf-8";
//m_ObjRequest.ContentLength = 500;
m_ObjRequest.KeepAlive = false;
m_ObjResponse = (HttpWebResponse)m_ObjRequest.GetResponse(); // getting response from the server
using (reader = new StreamReader(m_ObjResponse.GetResponseStream())) // using stream reader to read the web page
{
m_Response = reader.ReadToEnd();
reader.Close(); // Close the StreamReader
}
m_ObjResponse.Close();
m_ObjRequest = null;
m_ObjResponse = null;
My php code to handle this encoded bitmap string is as follows:
$bitmap=$_GET['bitmap'];
$data = base64_decode($bitmap);
$im = imagecreatefromstring($data);
if ($im !== false) {
header('Content-Type: image/png');
imagepng($im);
imagedestroy($im);
}
else {
echo 'An error occurred.';
}
encoded bitmap string is as follows:
$bitmap="Qk02BAAAAAAAADYAAAAoAAAAEAAAABAAAAABACAAAAAAAAAAAADEDgAAxA4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA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AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=="
why i am getting this error on imagecreate from string?
BMP format is not supported by imagecreatefromstring. Allowed formats are: JPEG, PNG, GIF, WBMP, and GD2.
Have an issue with Air application and upload the image to server by php.
What I'm doing wrong? On progress everything is alright, is showing progress and response, but php can't find an image.
var request:URLRequest = new URLRequest("http://xxxxxxxxxx/api.php");
request.method = URLRequestMethod.POST;
request.contentType = "application/octet-stream";
var variables:URLVariables = new URLVariables();
variables.action = "addEntry";
variables.user = "1";
request.data = variables;
var file:FileReference = new FileReference();
var filenameSmall:String = "xxxxx/" + _userName+"/thumbnail.jpg";
if(_fb == true)
{
filenameSmall = "xxxxx/" + user +"/thumbnail.jpg";
}
file = File.desktopDirectory.resolvePath( filenameSmall );
file.addEventListener(ProgressEvent.PROGRESS, uploadProgress);
file.addEventListener(DataEvent.UPLOAD_COMPLETE_DATA, uploadDataComplete);
file.addEventListener(SecurityErrorEvent.SECURITY_ERROR, uploadError);
file.addEventListener(HTTPStatusEvent.HTTP_STATUS, uploadError);
file.addEventListener(IOErrorEvent.IO_ERROR, uploadError);
file.upload(request, "image");
The upload of file reference could not send any request or variables to php files. It just upload the file to the path you have given in the url. If you want to save an image using php
you should convert the image to byte array,
Do any one the encoding process(either PNGEncoding or JPEGEncoding),
If you want then do any standard encoding(base64) for security
Then send that string to php
Make your php file to read that data and write it.
this is my first post. please be kind :)
i'm trying to get picture from media library (in WP 7), upload it using httpwebrequest, and save it to folder in the server. i succeed to convert the image to string of byte (but i suspect there are something wrong here), send the string using POST, and retrieve it in my php web page.
Everything seems to be working well, but when i convert the string of byte to jpeg (using imagecreatefromstring function) it always come up empty picture. here is my code in C# and php. I'm sorry for my English if it's not perfect (or far from perfect) :)
this is my c# code along with some comments
public partial class MainPage : PhoneApplicationPage
{
string uploadUri = #"http://192.168.138.1/meeshot/upload.php"; //php web page for retrieve and saving file in the server
string requestImageName = "picture"; //variable name for post ---- >$_POST['picture']
string postdata; //byte data generate using BitmapToByte function
// Constructor
public MainPage()
{
InitializeComponent();
}
PhotoChooserTask selectphoto = null;
Image image1 = new Image ();
private void button1_Click(object sender, RoutedEventArgs e) //user choosing photo from media library
{
selectphoto = new PhotoChooserTask();
selectphoto.Completed += new EventHandler<PhotoResult>(selectphoto_Completed);
selectphoto.Show();
}
void selectphoto_Completed(object sender, PhotoResult e)
{
if (e.TaskResult == TaskResult.OK)
{
BinaryReader reader = new BinaryReader(e.ChosenPhoto);
image1.Source = new BitmapImage(new Uri(e.OriginalFileName));
HttpWebRequest req = HttpWebRequest.Create(
new Uri(this.uploadUri)) as HttpWebRequest;
postdata = BitmapToByte(image1); //convert image to byte. My suspisicion there is something wrong here
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
req.BeginGetRequestStream(HttpWebRequestButton2_RequestCallback, req);
}
}
private void HttpWebRequestButton2_RequestCallback(IAsyncResult result)
{
var req = result.AsyncState as HttpWebRequest;
using (var requestStream = req.EndGetRequestStream(result))
{
using (StreamWriter writer = new StreamWriter(requestStream))
{
writer.Write(requestImageName+"="+this.postdata); //writing "picture=bytedata"
writer.Flush();
}
}
req.BeginGetResponse(HttpWebRequestButton_Callback, req);
}
private void HttpWebRequestButton_Callback(IAsyncResult result)
{
var req = result.AsyncState as HttpWebRequest;
var resp = req.EndGetResponse(result);
var strm = resp.GetResponseStream();
var reader = new StreamReader(strm);
this.Dispatcher.BeginInvoke(() => {
this.DownloadedText.Text = reader.ReadToEnd(); //the web page will print byte data that has been sent using httpwebrequest. i can see that byte data has benn sent sucessfuly.
this.DownloadedText.Visibility = System.Windows.Visibility.Visible;
});
}
private Stream ImageToStream(Image image1)
{
WriteableBitmap wb = new WriteableBitmap(400, 400);
wb.Render(image1, new TranslateTransform { X = 400, Y = 400 });
wb.Invalidate();
Stream myStream = new MemoryStream();
wb.SaveJpeg(myStream, 400, 400, 0, 70);
return myStream;
}
private string BitmapToByte(Image image) //i suspect there is something wrong here
{
Stream photoStream = ImageToStream(image);
BitmapImage bimg = new BitmapImage();
bimg.SetSource(photoStream); //photoStream is a stream containing data for a photo
byte[] bytearray = null;
using (MemoryStream ms = new MemoryStream())
{
WriteableBitmap wbitmp = new WriteableBitmap(bimg);
wbitmp.SaveJpeg(ms, wbitmp.PixelWidth, wbitmp.PixelHeight, 0, 100);
ms.Seek(0, SeekOrigin.Begin);
bytearray = ms.GetBuffer();
}
string str = Convert.ToBase64String(bytearray);
return str;
}
and this is my code in php web page
if(isset($_REQUEST['picture'])) //check
{
$myFile = "picture.jpg";
$fh = fopen($myFile, 'wb') or die("can't open file");
$stringData = $_REQUEST['picture']."<br>";
$im = imagecreatefromstring($stringData);
if ($im) {
imagejpeg($im);
fwrite($fh, $im);
imagedestroy($im);
}
fclose($fh);
echo $stringData;
}
Please look at my question here: Photo upload with parameters to a PHP page
And my solution here: http://nediml.wordpress.com/2012/05/10/uploading-files-to-remote-server-with-multiple-parameters/