Failed to upload picked image from gallery to php server - php

I'm using PHP for a project that needs to be able to upload images from a gallery. For now I'm trying this:
I'm trying to pick image from gallery using httpClient and upload it to php serve. What works from is - pick image, convert mediafile to base64, but when it comes to php it recieves image file but doesn't add it to folder and always returns failed upload.
Where am I mistaken?
Here is my code:
private async void browse_image(object sender, EventArgs e)
{
await CrossMedia.Current.Initialize();
var file = await CrossMedia.Current.PickPhotoAsync();
MF = file;
if (file == null)
return;
string[] stringSeparators = new string[] { "." };
var result = file.Path.Split(stringSeparators, StringSplitOptions.None);
img_path.Text = u.Username + code.Text + "." + result[1];
var stream = file.GetStream();
profile.Source = ImageSource.FromStream(() =>
{
return stream;
});
}
public bool convert_image_to64(){
var stream = MF.GetStream();
byte[] filebytearray = new byte[stream.Length];
stream.Read(filebytearray, 0, (int)stream.Length);
base64 = Convert.ToBase64String(filebytearray);
if(String.IsNullOrEmpty(base64)){
return false;
}
return true;
}
async Task upload_profile_page()
{
try
{
string result = "";
var postData = new List<KeyValuePair<string, string>>();
postData.Add(new KeyValuePair<string, string>("image", base64));
postData.Add(new KeyValuePair<string, string>("filename", img_path.Text));
var stringPayload = JsonConvert.SerializeObject(postData);
var content = new StringContent(stringPayload, Encoding.UTF8, "application/json");
await DisplayAlert("", content.ToString(), "ok");
HttpClient client = new HttpClient();
var response = await client.PostAsync("http://example.com/upload_app.php", content);
var FinalJSonResult =. (JArray)JsonConvert.DeserializeObject(response.Content.ReadAsStringAsync().Result);
if (FinalJSonResult.Count > 0)
{
var j = (JObject)FinalJSonResult[0];
result = j.GetValue("result").ToString();
if (result.Equals("0"))
{
await DisplayAlert("0 ->", "failed to upload", "ok");
}
else if (result.Equals("1"))
{
await DisplayAlert("1 ->", "uploaded image successffully", "ok");
}
else
{
await DisplayAlert("1 ->", result, "ok");
}
}
else
{
await DisplayAlert("Error", "Empty result" + "\n" + "size of returned array:- " + FinalJSonResult.Count.ToString(), "Ok");
}
}
catch (Exception ex)
{
await DisplayAlert("Error", ex.ToString(), "Ok");
return;
}
}
<?php // read JSon input
$data_back = json_decode(file_get_contents('php://input'));
// set json string to php variables
$base = $data_back->{"image"};
$filename = $data_back->{"filename"};
$binary=base64_decode($base);
$result1 = array();
header("Content-type: application/json");
try{ // Decode Image
$binary=base64_decode($base);
header('Content-Type: bitmap; charset=utf-8');
$result1 = array();
// Images will be saved under '.../uplodedimages' folder
$file = fopen('.../uplodedimages/'.$filename, 'wb');
// Create File
if(fwrite($file, $binary)==false){
array_push($result1,array( 'result'=>"0"));
}else{
$result1 = array();
array_push($result1,array( 'result'=>"1"));
}
fclose($file);
}catch(Exception $e) {
array_push($result1,array( 'result'=>$e));
}
echo json_encode($result1,JSON_UNESCAPED_UNICODE);
?>

Related

Uploading SVG Laravel 5.5

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

could not be able to upload file to server using retrofit2

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 :)

PHP can not find files in windows

I have build a server use PHP based on WAMP Server on my windows 10 computer. what I want to do is when I send a GET request, the show_files.php should return a JSON object to me. The JSON object contains file names in path F:\NetEaseMusic\download on my computer. Then I use a file name to send a POST request to download_file.php and it returns a data stream so that I can download file. When I use HttpURLConnection, everything works well. However, when I try send the POST request use socket, download_file.php can get the file_name param, but it can not find the target file in F:\NetEaseMusic\download. I show the code.
this is
this is download_file.php
<?php
if(empty($_POST["file_name"]))
{
echo "NO_FILE_NAME\n";
print_r($_POST);
exit();
}
$path = iconv("utf-8", "GB2312","F:\\NetEaseMusic\\download\\".$_POST["file_name"]);
//$path = "F:\\NetEaseMusic\\download\\".$_POST["file_name"];
if (!file_exists ( $path )) {
echo "FILE_NOT_FOUND\n";
echo "F:\\NetEaseMusic\\download\\".$_POST["file_name"]."\n";
print($path);
exit ();
}
$file_size = filesize($path);
//header("Content-type: application/octet-stream");
//header("Accept-Ranges: bytes");
//header("Accept-Length:".$file_size);
//header("Content-Disposition: attachment; filename=".$path);
$file = fopen($path, "r");
while(!feof($file))
{
echo fread($file, 1024);
}
exit();
?>
this is my Client code which to download file. First of all I build a HTTP POST request,
private void downloadFileBySocket(String urlString, String fileName)
{
try{
StringBuilder sb = new StringBuilder();
String data = URLEncoder.encode("file_name", "utf-8") + "=" + URLEncoder.encode(fileName, "utf-8") + "\r\n";
//String data = "&file_name="+fileName;
sb.append("POST " + urlString + " HTTP/1.1\r\n");
sb.append("Host: 10.206.68.242\r\n");
sb.append("Content-Type: application/x-www-form-urlencoded\r\n");
sb.append("Content-Length: " + data.length() + "\r\n");
sb.append("\r\n");
sb.append(data + "\r\n");
//sb.append( URLEncoder.encode("file_name", "utf-8") + "=" + URLEncoder.encode(fileName, "utf-8") + "\r\n");
System.out.println(sb.toString());
URL url = new URL(urlString);
Socket socket = new Socket(url.getHost(), url.getPort());
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), "utf-8"));
writer.write(sb.toString());
writer.flush();
File file = new File("./" + fileName);
DataOutputStream out = null;
DataInputStream in = null;
try{
out = new DataOutputStream(new FileOutputStream(file));
in = new DataInputStream(socket.getInputStream());
byte[] buffer = new byte[1024];
int readBytes = 0;
while((readBytes = in.read(buffer)) != -1)
{
out.write(buffer, 0, readBytes);
}
out.flush();
}catch (Exception e1)
{
e1.printStackTrace();
}finally {
try{
if(in != null)
{
in.close();
}
if(out != null)
{
out.close();
}
}catch (Exception e2)
{
e2.printStackTrace();
}
}
socket.close();
}catch (Exception e)
{
e.printStackTrace();
}
}
and my main[] method
public static void main(String[] args)
{
SocketTest socketTest = new SocketTest();
socketTest.downloadFileBySocket(SocketTest.downloadFileUrl, "小胡仙儿 - 【二胡】霜雪千年.mp3");
}
Simple way:
using System.Net;
WebClient webClient = new WebClient();
webClient.DownloadFile("example.com/myfile.txt", #"c:/myfile.txt");

Get location from image in android to php and sometimes error couldn't get location

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);
}
}

Uploading picture from xamarin form to a php server

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().'"}';
}

Categories