First of all, thank you for reading my question.
I have a PHP server where I wanted to upload an image from Android devices.
When I pick an image in my phone, it is uploaded as a TypedFile (retrofit.mime.TypedFile) to a PHP script.
When I want to see the image using a web browser or download the image with FTP client, the image is corrupted.
The Log shows me the image bytes and the downloaded file contains these bytes.
The first line of the image bytes is:
RIFF WEBPVP8 „ ¥ *,>Ñ`©P(%$##‘Œ9 i;\·û~œdàþ ÚKfëp‡ö~
(WebP mime type?)
My PHP script looks like this:
[...]
$pic = 'uploaded_images/' . $imagename . '.jpg';
if (!move_uploaded_file($_FILES['image']['tmp_name'], $pic)) {
echo "ko";die;
}
[...]
I have also tried fread, fwrite,... and this:
$file = file_get_contents($_FILES['image']['tmp_name']);
if (!$file) {echo 'file ko';die;}
//$file = unpack('h',$file);
if (!file_put_contents($pic, $file)) {echo 'ko';die;}
And some other combinations.
My Android request is (from Intent.ACTION_PICK or Intent.ACTION_IMAGE_CAPTURE):
#Override
public void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) {
super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
switch (requestCode) {
case SELECT_PHOTO:
if (resultCode == Activity.RESULT_OK) {
final boolean isCamera;
if (imageReturnedIntent == null) {
isCamera = true;
} else {
final String action = imageReturnedIntent.getAction();
if (action == null) {
isCamera = false;
} else {
isCamera = action.equals(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
}
}
Uri selectedImageUri;
if (isCamera) {
selectedImageUri = outputFileUri;
} else {
selectedImageUri = imageReturnedIntent == null ? null : imageReturnedIntent.getData();
}
if (selectedImageUri != null) {
String selectedImagePath = null;
Cursor cursor = getActivity().getContentResolver().query(selectedImageUri, null, null, null, null);
if (cursor == null) {
selectedImagePath = selectedImageUri.getPath();
} else {
cursor.moveToFirst();
int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
selectedImagePath = cursor.getString(idx);
}
File photo = new File(selectedImagePath);
TypedFile typedImage = new TypedFile("image/*", photo);
// ProgressDialog lazy initialization
if (progress == null) {
progress = new ProgressDialog(getActivity());
progress.setTitle(getString(R.string.updating_data));
progress.setMessage(getString(R.string.please_wait));
progress.setCancelable(false);
progress.setIndeterminate(true);
}
progress.show();
Server.postUserImage(typedImage, imageCallback);
}
}
}
}
Server.postUserImage is a method where I configure the request.
The retrofit request interface is:
#Multipart
#POST("/user/image")
void postUserImage(#Part("image") TypedFile image, Callback<User> callback);
I appreciate so much your help. I have spent hours a couple of days looking for the reason and a solution for this.
Thank you very much.
I have solved it.
In case anyone has the same issue:
The bug was the mime type of the sended file: "image/*". For some reason, my PHP code is unable to save some images.
I have changed it to "application/octet-stream" and it works like a charm!
This is the old code:
File photo = new File(selectedImagePath);
TypedFile typedImage = new TypedFile("image/*", photo);
And this is the new code:
File photo = new File(selectedImagePath);
TypedFile typedImage = new TypedFile("application/octet-stream", photo);
Related
My retrofit instance is working fine with localhost (both android code and postman), and working fine online with postman. But when I go to Amazon AWS instance (a.k.a online) the android part is not working. Please see my code below. The error log from android is D/response: {"error":true,"message":"Required parameters are not available"}
Interestingly the problem is with large file sizes 2M, small file sizes 24KB are getting uploaded fine. I have already checked the php.ini file the max sizes there are 25MB
I am following this tutorial : https://www.simplifiedcoding.net/retrofit-upload-file-tutorial/
public interface Api {
//the base URL for our API
//make sure you are not using localhost
//find the ip usinc ipconfig command
String BASE_URL = "http://creative-thinker.com/files/images/secret_crushes/";
//this is our multipart request
//we have two parameters on is name and other one is description
#Multipart
#POST("Api.php?apicall=upload")
Call<MyResponse> uploadImage(#Part("image\"; filename=\"myfile.jpg\" ")
RequestBody file, #Part("desc") RequestBody desc);
}
My Object Class
public class MyResponse {
public boolean error;
String message;
}
My Fragment
ivImageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Open The File Choose And Send To Activity For Result
Intent i = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, 100);
}
});
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 100 && data != null) {
//the image URI
Uri selectedImage = data.getData();
//calling the upload file method after choosing the file
uploadFile(selectedImage, "My Image");
}
}
private void uploadFile(Uri fileUri, String desc) {
//creating a file
File file = new File(getRealPathFromURI(fileUri));
//creating request body for file
RequestBody requestFile = RequestBody.create(MediaType.parse(getContext().getContentResolver().getType(fileUri)), file);
RequestBody descBody = RequestBody.create(MediaType.parse("text/plain"), desc);
//The gson builder
Gson gson = new GsonBuilder()
.setLenient()
.create();
//creating retrofit object
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(Api.BASE_URL)
.addConverterFactory(GsonConverterFactory.create(gson))
.build();
//creating our api
Api api = retrofit.create(Api.class);
//creating a call and calling the upload image method
Call<MyResponse> call = api.uploadImage(requestFile, descBody);
//finally performing the call
call.enqueue(new Callback<MyResponse>() {
#Override
public void onResponse(Call<MyResponse> call, Response<MyResponse> response) {
if (!response.body().error) {
Toast.makeText(getContext().getApplicationContext(), "File Uploaded Successfully...", Toast.LENGTH_LONG).show();
} else {
MyResponse res= response.body();
Log.d("response", new Gson().toJson(res));
Toast.makeText(getContext().getApplicationContext(), "Some error occurred...", Toast.LENGTH_LONG).show();
}
}
#Override
public void onFailure(Call<MyResponse> call, Throwable t) {
Toast.makeText(getContext().getApplicationContext(), t.getMessage(), Toast.LENGTH_LONG).show();
}
});
}
/*
* This method is fetching the absolute path of the image file
* if you want to upload other kind of files like .pdf, .docx
* you need to make changes on this method only
* Rest part will be the same
* */
private String getRealPathFromURI(Uri contentUri) {
String[] proj = {MediaStore.Images.Media.DATA};
CursorLoader loader = new CursorLoader(getContext(), contentUri, proj, null, null, null);
Cursor cursor = loader.loadInBackground();
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String result = cursor.getString(column_index);
cursor.close();
return result;
}
FileHandler.php
<?php
class FileHandler
{
private $con;
public function __construct()
{
require_once dirname(__FILE__) . '/DbConnect.php';
$db = new DbConnect();
$this->con = $db->connect();
}
public function saveFile($file, $extension, $desc)
{
$name = round(microtime(true) * 1000) . '.' . $extension;
$filedest = dirname(__FILE__) . UPLOAD_PATH . $name;
move_uploaded_file($file, $filedest);
$url = $server_ip = gethostbyname(gethostname());
$stmt = $this->con->prepare("INSERT INTO images (description, image) VALUES (?, ?)");
$stmt->bind_param("ss", $desc, $name);
if ($stmt->execute()) {
return true;
}
return false;
}
public function getAllFiles()
{
$stmt = $this->con->prepare("SELECT id, description, image FROM images ORDER BY id DESC");
$stmt->execute();
$stmt->bind_result($id, $desc, $url);
$images = array();
while ($stmt->fetch()) {
$temp = array();
$absurl = 'http://' . gethostbyname(gethostname()) . '/files/images/secret_crushes' . UPLOAD_PATH . $url;
$temp['id'] = $id;
$temp['desc'] = $desc;
$temp['url'] = $absurl;
array_push($images, $temp);
}
return $images;
}
}
Api.php
<?php
require_once dirname(__FILE__) . '/FileHandler.php';
$response = array();
if (isset($_GET['apicall'])) {
switch ($_GET['apicall']) {
case 'upload':
if (isset($_POST['desc']) && strlen($_POST['desc']) > 0 && $_FILES['image']['error'] === UPLOAD_ERR_OK) {
$upload = new FileHandler();
$file = $_FILES['image']['tmp_name'];
$desc = $_POST['desc'];
if ($upload->saveFile($file, getFileExtension($_FILES['image']['name']), $desc)) {
$response['error'] = false;
$response['message'] = 'File Uploaded Successfullly';
}
} else {
$response['error'] = true;
$response['message'] = 'Required parameters are not available';
}
break;
case 'getallimages':
$upload = new FileHandler();
$response['error'] = false;
$response['images'] = $upload->getAllFiles();
break;
}
}
echo json_encode($response);
function getFileExtension($file)
{
$path_parts = pathinfo($file);
return $path_parts['extension'];
}
I am trying to catch the values of items in Api.php using
$response['message'] = $string; just where $response['message'] = 'Required parameters are not available';
and getting the following results
$string = $_POST['desc'];
D/response: {"error":true,"message":"My Image"}
$string = $_POST['desc'];
$string = strlen($string);
D/response: {"error":true,"message":"8"}
$string = $_FILES['image']['error'];
D/response: {"error":true}
$string = UPLOAD_ERR_OK;
D/response: {"error":true,"message":"0"}
And removing && $_FILES['image']['error'] === UPLOAD_ERR_OK enters the data into database but no image still uploaded
Finally found the solution after searching the net... The issue was file size
I am on php 7 and Apache. So the configuration needs to changed at two places
The configuration
upload_max_filesize = 25M
post_max_size = 25M
max_execution_time = 300
max_input_time = 300
memory_limit = 128M
The locations
sudo nano /etc/php/7.0/fpm/php.ini
sudo nano /etc/php/7.0/apache2/php.ini
Apparently the settings needs to be changed for PHP AND Apache on Amazon AWS. Hope it helps others.
How do I properly upload a svg file with Laravel 5.5?
The standard image validation rule does not see it as a proper image (image|mimes:jpeg,png,jpg,gif,svg)
When I remove all validation, the file get's stored as a txt file.
My upload code:
$request->file('image')->store('images', 'public');
This Will Work
Use Like This Will Work
if ($request->hasFile('file')) {
$file = $request->file('file');
$file->move($file, 'uploads/audio');
}
from a svg string creating a file, I didn't succeed with string sending as it abuses about some wrong chars after it been transmited to Laravel. So far from Android by okhttp:
private static final MediaType MEDIA_TYPE_TXT =MediaType.parse("text/plain");
....
MultipartBody.Builder obj_ = new MultipartBody.Builder().setType(MultipartBody.FORM);
fileImzo_ = new File(fileSafar_.getAbsoluteFile().getParentFile().getAbsolutePath(),"imzo.txt");
String nomiImzo_ = fileImzo_.getName();
//svgImzo is a raw SVG xml string
InputStream stream_ = new ByteArrayInputStream(svgImzo.getBytes(StandardCharsets.UTF_8));
try {
try (OutputStream output_ = new FileOutputStream(fileImzo_)) {
byte[] buffer = new byte[4 * 1024]; // or other buffer size
int read;
while ((read = stream_.read(buffer)) != -1) {
output_.write(buffer, 0, read);
}
output_.flush();
}
}catch(Exception e){
e.printStackTrace();
} finally {
try {
stream_.close();
} catch (IOException e) {
e.printStackTrace();
}
}
obj_.addFormDataPart("fileImzo", nomiImzo_, RequestBody.create(fileImzo_, MEDIA_TYPE_TXT));
}
RequestBody req = obj_
.addFormDataPart("copayDodmi", "" + copayDodmi)
.addFormDataPart("izoh", xavar.getText().toString())
.addFormDataPart("driver_id", "" + driverId_)
.build();
Request request = new Request.Builder()
.header("Authorization", "Bearer " + token)//Authorization
.url(MehmonxonaActivity.URLI_ASSOSI + "/supurdani_paket_dodashud")
.post(req)
.build();
....
in Laravel controller , say we add the file path to array to update a row in the table:
....
if ($request->hasFile('fileImzo')) {
$imzo_filename = $this->sozuNomiFaylate('fileImzo', $request);
if (!is_null($imzo_filename)) {
$arr['signature_svg'] = $imzo_filename;
}
}
....
and the function sozuNomiFaylate():
....
private function sozuNomiFaylate(string $alias, \Illuminate\Http\Request $request)
{
$separatorLcl = DIRECTORY_SEPARATOR;
$image = $request->file($alias);
$ext=$image->getClientOriginalExtension();
if($ext==='svg' || $ext==='SVG' || $ext==='txt'|| $ext==='')
$ext='svg';
$filename = time() . '.' .$ext ;
$path = public_path('images' . $separatorLcl . 'uploads' . $separatorLcl . $filename);
if($ext==='svg' || $ext==='SVG' || $ext==='txt'|| $ext===''){
File::put($path,$image->get());//Illuminate\Support\Facades\File
}else
try {
l::k($path);
Image::make($image)->save($path);
} catch (\Exception $e) {
l::k($e->getMessage());
l::k($e->getTraceAsString());
l::k('fayl soxta na shud');
return null;
}
return $filename;
}
....
And you are done
I want to upload .pdf file to server where php code is
<?php
$con = mysqli_connect("localhost","db_user","pwd","api_db");
$user_id = $_POST['id'];
$title = $_POST['cvTitle'];
$allowedExts = array("docx","doc", "pdf", "txt");
$temp = explode(".", $_FILES['cvfile']["name"]);
$extension = end($temp);
if ((($_FILES["cvfile"]["type"] == "application/pdf")
|| ($_FILES["cvfile"]["type"] == "application/text/plain")
|| ($_FILES["cvfile"]["type"] == "application/msword")
|| ($_FILES["cvfile"]["type"] == "application/vnd.openxmlformats-officedocument.wordprocessingml.document"))
&& in_array($extension, $allowedExts)){
//inner if
if ($_FILES["cvfile"]["error"] > 0){
echo "Failed 1";
} else{
}// end inner else
$f_name = time().$_FILES['cvfile']["name"];
move_uploaded_file($_FILES['cvfile']["tmp_name"],
"upload/" . $f_name);
$file_name = $f_name;
} else {
$json = array("File Type Not Allowed");
header('content-type: application/json');
echo json_encode($json);
} // end else
$query = "UPDATE users set cv = '$file_name', cvTitle = '$title' where id = '$user_id'";
if (mysqli_query($db,$query)) {
$json = array("cv" => $file_name, "cvTitle" => $title);
header('content-type: application/json');
echo json_encode($json);
}
?>
my service is
#FormUrlEncoded
#Multipart
#POST("updatecv.php")
Call<User> uploadUserCV(#Field("id") String id,
#Field("cvTitle") String cvTitle,
#Part MultipartBody.Part cv);
and finally I'm making call as
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.action_cv : {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("*/*");
startActivityForResult(Intent.createChooser(intent, "Choose file using"), Constant.REQUEST_CODE_OPEN);
return true;
}
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try {
if (requestCode == Constant.REQUEST_CODE_OPEN){
if (resultCode == RESULT_OK && null != data){
String type = Utils.getMimeType(UpdateProfileActivity.this, data.getData());
if (validateFileType(type)){
// Get the Image from data
Uri selectedFile = data.getData();
String[] filePathColumn = {MediaStore.Files.FileColumns.DATA};
Cursor cursor = getContentResolver().query(selectedFile, filePathColumn, null, null, null);
assert cursor != null;
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
mediaPath = cursor.getString(columnIndex);
cursor.close();
uploadFile();
} else {
Toast.makeText(UpdateProfileActivity.this, "File type is not allowed", Toast.LENGTH_SHORT).show();
}
Log.e("FILE_TYPE", Utils.getMimeType(UpdateProfileActivity.this, data.getData()));
}
}
} catch (Exception e){
e.printStackTrace();
}
}
// Uploading CV
private void uploadFile() {
final Dialog dialog = Utils.showPreloaderDialog(UpdateProfileActivity.this);
dialog.show();
// Map is used to multipart the file using okhttp3.RequestBody
File file = new File(mediaPath);
// Parsing any Media type file
final RequestBody requestBody = RequestBody.create(MediaType.parse("*/*"), file);
MultipartBody.Part fileToUpload = MultipartBody.Part.createFormData("file", file.getName(), requestBody);
mUserCall = mRestManager.getApiService().uploadUserCV(uid, file.getName(), fileToUpload);
mUserCall.enqueue(new Callback<User>() {
#Override
public void onResponse(Call<User> call, Response<User> response) {
User user = response.body();
Log.e("UPLOADED_FILE", "name is " + user.getCvTitle());
dialog.dismiss();
}
#Override
public void onFailure(Call<User> call, Throwable t) {
dialog.dismiss();
Log.e("UPLOADED_FILE_ERROR", "Message is " + t.getMessage());
Toast.makeText(UpdateProfileActivity.this, "Something went wrong", Toast.LENGTH_SHORT).show();
}
});
}
private boolean validateFileType(String type){
String [] allowedFileTypes = {"application/vnd.openxmlformats-officedocument.wordprocessingml.document",
"application/msword", "text/plain", "application/pdf"};
for (int i = 0; i<=allowedFileTypes.length; i++){
if (allowedFileTypes[i].equals(type)){
return true;
}
}
return false;
}
but this code is not uploading the file to server no any errors. I wan to know where are the things wrong in php code or in android side.
Any help is highly appreciated.
According to your PHP, you're looking for form-data part with name cvfile, but in Android code you're passing file as a name of the form-data part. So all you need is to change file to cvfile, like this:
MultipartBody.Part fileToUpload = MultipartBody.Part.createFormData("cvfile", file.getName(), requestBody);
Hopefully it should work.
It seems you are testing on localhost then inside app localhost url is needed ....to grab that
type ipconfig (in cmd on windows)
copy that ip which is connected to lan or wifi.
then check is upload.php file present or not on that ip address.
for eg : 192.168.1.102/upload.php
after that copy the ip and
add in base url of retrofit builder in retrofit client class.
Hope it will solve your issue :)
I'm using AS
first case : I'm running android app from PC A to device kitkat and marshmallow, then I'm trying to upload image to server and get the location using PHP. the result is when using device kitkat the GPS I can get it, but no in marshmallow
second case : I'm running android app from PC B, to device kitkat and marshmallow, then I'm trying to upload image to server and get the location using PHP. the result is I'm using kitkat and marshmallow the both cannot get GPS from image
third case : I'm running android app from PC B to device kitkat and marshmallow, then I'm trying to upload image to server and get the location using PHP. BUT for now I change the IP to connect server using IP on PC A. the result is when I using device kitkat the GPS I can get it, but using Marshmallow still cannot get the location
in code I have already using android runtime permission. there's no logcat error
how I can fix that?
and this code PHP
<?php
error_reporting(0);
$latitude = 0;
$longitude = 0;
$lokasi = "uploads/";
$file_name = $_FILES['image']['name'];
$file_ext = explode('.',$file_name);
$file_ext = strtolower(end($file_ext));
$file_size = $_FILES['image']['size'];
$file_tmp = $_FILES['image']['tmp_name'];
$filename = basename($_FILES['image']['name']);
$target_path = $lokasi . basename($_FILES['image']['name']);
echo basename($_FILES['image']['name'])."<BR>";
//get latitude and longitude
$image_file = $file_tmp;
echo "string : ".$image_file;
if(file_exists($image_file)){
$details = exif_read_data($image_file);
$sections = explode(',',$details['SectionsFound']);
if(in_array('GPS',array_flip($sections))){
echo $latitude = number_format(format_gps_data($details['GPSLatitude'],$details['GPSLatitudeRef']),10, ',', ' ');
$longitude = number_format(format_gps_data($details['GPSLongitude'],$details['GPSLongitudeRef']),10, ',', ' ');
}
else{
die('GPS data not found');
}
}
else{
die('File does not exists');
}
function format_gps_data($gpsdata,$lat_lon_ref){
$gps_info = array();
foreach($gpsdata as $gps){
list($j , $k) = explode('/', $gps);
array_push($gps_info,$j/$k);
}
$coordination = $gps_info[0] + ($gps_info[1]/60.00) + ($gps_info[2]/3600.00);
return (($lat_lon_ref == "S" || $lat_lon_ref == "W" ) ? '-'.$coordination : $coordination).' '.$lat_lon_ref;
}
///////////////////////////////
$nama_file = $latitude . "_" . $longitude . "." . $file_ext;
$target_path=$lokasi . $nama_file;
try {
//throw exception if can't move the file
if (!move_uploaded_file($file_tmp, $target_path)) {
throw new Exception('Could not move file');
}
echo "Success";
} catch (Exception $e) {
die('File did not upload: ' . $e->getMessage());
}
?>
and this code for upload image
private class UploadFileToServer extends AsyncTask<Void, Integer, String> {
#Override
protected void onPreExecute() {
// setting progress bar to zero
progressBar.setProgress(0);
super.onPreExecute();
}
#Override
protected void onProgressUpdate(Integer... progress) {
// Making progress bar visible
progressBar.setVisibility(View.VISIBLE);
// updating progress bar value
progressBar.setProgress(progress[0]);
// updating percentage value
txtPercentage.setText(String.valueOf(progress[0]) + "%");
}
#Override
protected String doInBackground(Void... params) {
return uploadFile();
}
#SuppressWarnings("deprecation")
private String uploadFile() {
String responseString = null;
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(Config.FILE_UPLOAD_URL);
try {
AndroidMultiPartEntity entity = new AndroidMultiPartEntity(
new ProgressListener() {
#Override
public void transferred(long num) {
publishProgress((int) ((num / (float) totalSize) * 100));
}
});
File sourceFile = new File(filePath);
// Adding file data to http body
entity.addPart("image", new FileBody(sourceFile));
image = new FileBody(sourceFile);
// Extra parameters if you want to pass to server
entity.addPart("website",
new StringBody("www.androidhive.info"));
entity.addPart("email", new StringBody("abc#gmail.com"));
totalSize = entity.getContentLength();
httppost.setEntity(entity);
// Making server call
HttpResponse response = httpclient.execute(httppost);
HttpEntity r_entity = response.getEntity();
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == 200) {
// Server response
responseString = EntityUtils.toString(r_entity);
} else {
responseString = "Error occurred! Http Status Code: "
+ statusCode;
}
} catch (ClientProtocolException e) {
responseString = e.toString();
} catch (IOException e) {
responseString = e.toString();
}
return responseString;
}
#Override
protected void onPostExecute(String result) {
Log.e(TAG, "Response from server: " + result);
// showing the server response in an alert dialog
showAlert(result);
super.onPostExecute(result);
}
}
Please I have been trying to upload pictures from a xamarin form application to a php server but seems not to be working. The server receives an empty $_FILES request. This is the c# code.
public async Task<bool> Upload(MediaFile mediaFile, string filename)
{
byte[] bitmapData;
var stream = new MemoryStream();
mediaFile.GetStream().CopyTo(stream);
bitmapData = stream.ToArray();
var fileContent = new ByteArrayContent(bitmapData);
fileContent.Headers.ContentType = MediaTypeHeaderValue.Parse("application/octet-stream");
fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
{
Name = "fileUpload",
FileName = filename
};
string boundary = "---8393774hhy37373773";
MultipartFormDataContent multipartContent = new MultipartFormDataContent(boundary);
multipartContent.Add(fileContent);
HttpClient httpClient = new HttpClient();
HttpResponseMessage response = await httpClient.PostAsync("http://www.url.com/upload.php", multipartContent);
response.EnsureSuccessStatusCode();
if (response.IsSuccessStatusCode)
{
string content = await response.Content.ReadAsStringAsync();
return true;
}
return false;
}
Below is the php file to receive the uploaded image. I tried to save the content of the posted image to file but the file only has an empty array and always return "failure". Please what am i missing wrong? I have searched the web but cant seem to understand the problem.
$uploads_dir = 'uploads/';
$req_dump = print_r( $_FILES, true );
$fp = file_put_contents( 'data.txt', $req_dump );
if (isset($_FILES["fileUpload"]["tmp_name"]) AND is_uploaded_file($_FILES["fileUpload"]["tmp_name"]))
{
$tmp_name = $_FILES["fileUpload"]["tmp_name"];
$name = $_FILES["fileUpload"]["name"];
$Result = move_uploaded_file($tmp_name, "$uploads_dir/$name");
echo "Success";
}
else
{
echo "Failure";
}
The AND operator is really not a good choice for you. (On line 4).
Sometimes it shows some really unexpected behaviour. (I can refer you to 'AND' vs '&&' as operator for more info).
If you want a logical AND use the && operator instead.
The line would be
if (isset($_FILES["fileUpload"]["tmp_name"]) && is_uploaded_file($_FILES["fileUpload"]["tmp_name"]))
I know this is an old post but this is how I upload an image from Xamarin Forms to PHP
http://gjhdigital.com/xamarin/xamarin-forms-upload-image-to-php/
Xamarin c# code
using Plugin.Media;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
namespace UploadPicToServer
{
// Learn more about making custom code visible in the Xamarin.Forms previewer
// by visiting https://aka.ms/xamarinforms-previewer
[DesignTimeVisible(false)]
public partial class MainPage : ContentPage
{
public MainPage()
{
InitializeComponent();
}
private async void btnUpload_Clicked(object sender, EventArgs e)
{
if (!CrossMedia.Current.IsPickPhotoSupported)
{
await DisplayAlert("Photos Not Supported", ":( Permission not granted to photos.", "OK");
return;
}
var file = await Plugin.Media.CrossMedia.Current.PickPhotoAsync(new Plugin.Media.Abstractions.PickMediaOptions
{
PhotoSize = Plugin.Media.Abstractions.PhotoSize.Medium,
});
if (file == null)
return;
string fileName = file.Path;
image.Source = ImageSource.FromStream(() =>
{
var stream = file.GetStream();
file.Dispose();
return stream;
});
//UploadImage1(file.AlbumPath);
UploadImage(file.GetStream(), fileName);
}
private async void UploadImage(Stream mfile, string fileName)
{
int authorID = 2;
string username = "yourusername";
var url = "https://yourwebsite.com/ba-add-profile-pic.php";
url += "?id="+ authorID +"&username="+ username; //any parameters you want to send to the php page.
try
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("https://yourwebsite.com/");
MultipartFormDataContent form = new MultipartFormDataContent();
//HttpContent content = new StringContent("fileToUpload");
//form.Add(content, "fileToUpload");
var stream = mfile;
StreamContent content = new StreamContent(stream);
//get file's ext
string fileExt = fileName.Substring(fileName.Length - 4);
string fName = "User-Name-Here-123" + fileExt.ToLower();
content.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
{
Name = "fileToUpload",
FileName = fName
};
form.Add(content);
var response = await client.PostAsync(url, form);
var result = response.Content.ReadAsStringAsync().Result;
}
catch (Exception e)
{
//debug
Debug.WriteLine("Exception Caught: " + e.ToString());
return;
}
}
public static byte[] ToArray(Stream s)
{
if (s == null)
throw new ArgumentNullException(nameof(s));
if (!s.CanRead)
throw new ArgumentException("Stream cannot be read");
MemoryStream ms = s as MemoryStream;
if (ms != null)
return ms.ToArray();
long pos = s.CanSeek ? s.Position : 0L;
if (pos != 0L)
s.Seek(0, SeekOrigin.Begin);
byte[] result = new byte[s.Length];
s.Read(result, 0, result.Length);
if (s.CanSeek)
s.Seek(pos, SeekOrigin.Begin);
return result;
}
}
}
PHP code
//parameters send in via querystring
if (!isset($_REQUEST['author']) || !isset($_REQUEST['username']) ) {
die('{"status" : "Bad", "reason" : "Invalid Access"}');
}
$userID = $_REQUEST['author'];
$isGood = false;
try{
$uploaddir = '../someFolderToStoreTheImage/';
$fileName = basename($_FILES['fileToUpload']['name']);
$uploadfile = $uploaddir . basename($_FILES['fileToUpload']['name']);
//CHECK IF ITS AN IMAGE OR NOT
$allowed_types = array ('image/jpeg', 'image/png', 'image/bmp', 'image/gif' );
$fileInfo = finfo_open(FILEINFO_MIME_TYPE);
$detected_type = finfo_file( $fileInfo, $_FILES['fileToUpload']['tmp_name'] );
if ( !in_array($detected_type, $allowed_types) ) {
die ( '{"status" : "Bad", "reason" : "Not a valid image"}' );
}
//
if (move_uploaded_file($_FILES['fileToUpload']['tmp_name'], $uploadfile)) {
//echo "File is valid, and was successfully uploaded.\n";
echo '{"status" : "Success", "reason" "'. $fileName .'"}';
$isGood = true;
} else {
//echo "Possible file upload attack!\n";
echo '{"status" : "Bad", "reason" : "Unable to Upload Profile Image"}';
}
}
catch(Exception $e) {
echo '{"status" : "Bad", "reason" : "'.$e->getMessage().'"}';
}