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
Related
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().'"}';
}
I'm trying to encode a .jpg file on my server and send the string back to my android app. The PHP encoding function doesn't seem to be working - I always get a null response.
...
} else if ($tag == 'getPhoto') {
$filePath = $_POST['filePath'];
$filePath = mysql_real_escape_string($filePath);
$photo_str = $db->getPhotoString($filePath);
$photo_str = mysql_real_escape_string($photo_str);
if (!empty($photo_str)) {
echo $photo_str;
} else {
echo 'Something went wrong while retrieving the photo.';
}
}
...
public function getPhotoString($filePath) {
$type = pathinfo($filePath, PATHINFO_EXTENSION);
$photoData = file_get_contents($filePath);
$photo_str = 'data:image/' . $type . ';base64,' . base64_encode($photoData);
// $photo_str = 'test_response';
return $photo_str;
}
I know my filepath is correct because when I change it I get an error that says the file/directory doesn't exist. And, the "test_response" works when I uncomment it. Please help!
UPDATE - relevant android code:
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(parameters));
HttpResponse response = httpClient.execute(httpPost);
photoString = convertResponseToString(response);
Log.d("string response", photoString);
public String convertResponseToString(HttpResponse response) throws IllegalStateException, IOException{
String res = "";
StringBuffer buffer = new StringBuffer();
is = response.getEntity().getContent();
int contentLength = (int) response.getEntity().getContentLength(); //getting content length…..
if (contentLength < 0) {
} else {
byte[] data = new byte[512];
int len = 0;
try {
while (-1 != (len = is.read(data))) {
buffer.append(new String(data, 0, len)); //converting to string and appending to stringbuffer…..
}
} catch (IOException e) {
e.printStackTrace();
}
try {
is.close(); // closing the stream…..
} catch (IOException e) {
e.printStackTrace();
}
res = buffer.toString(); // converting stringbuffer to string…..
}
//System.out.println("Response => " + EntityUtils.toString(response.getEntity()));
return res;
}
This is not an answer, only a suggestion but i'm not able to comment as i don't have enough reputation xD. Anyway, did you try to echo $photoData after
$photoData = file_get_contents($filePath);
to see if it's filled with something? Maybe you get a null result. Also, can you tell me what's $filePath value when taken from $_POST variable and when passed to getPhotoString($filePath) function? I'm thinking about something wrong with mysql_real_escape_string().
im using this code in the android app, to capture image from camera and send to a javascript file to send a php controller for create file and inset some info to mysql.
the process works fine but the result image is to small and really poor quality
if( ACTION_TAKE_PICTURE == requestCode )
{
Bundle extras = intent.getExtras();
Bitmap bitmap;
if( null == extras || null == (bitmap=(Bitmap)extras.get("data")) ) return;
ByteArrayOutputStream out = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
byte [] ba = out.toByteArray();
String b64img = Base64.encodeToString(out.toByteArray(), Base64.NO_WRAP);
try { out.close(); } catch(Exception e) {}
wv.loadUrl( String.format("%s%s('%s')", getString(R.string.js_call_prefix), getString(R.string.js_callback_camera), b64img ));
}
the php code is:
public function executeImagen(sfWebRequest $request) {
$id = $request->getParameter('id');
$img = $request->getParameter('img');
$category = $request->getParameter('category');
$user = $this->getUser()->getAttribute('id_users');
try {
$basepdir = $path = sfConfig::get("sf_upload_dir") . '/photos/';
$basename = date('Ymd_His');
$buffer = base64_decode(str_replace(' ', '+', $img));
$pname = sprintf("%s%s.JPG", $basepdir, $basename);
$photo = sprintf("%s.JPG", $basename);
$fd = fopen($pname, "wb");
if ($fd) {
fwrite($fd, $buffer);
fflush($fd);
fclose($fd);
}
} catch (Exception $exc) {
echo $exc->getTraceAsString();
}
try {
$tabla = Doctrine::getTable('StorePhotos');
$tabla = new StorePhotos();
$tabla->id_store = $id;
$tabla->id_category = $category;
$tabla->id_users = $user;
$tabla->imagen = $photo;
$tabla->photo_date = date('Y-m-d H:i:s');
$tabla->save();
} catch (Exception $e) {
trigger_error("ERROR: ", $e->getMessage());
}
return sfView::NONE;
}
thanks.
You are getting and sending the thumbnail. You need to retrieve the full-size image from disk instead. Read this guide by Google.