Attach file with spaces in the name - javascript

I can't attach files with spaces in the name, but when have no space
is successfully attached, i'm using codeigniter for this,
uploading the file to the server before attach it, i use the helper Path for get the routes to my file.
function upload_file() {
//$this->load->helper('path');
//$path = set_realpath('./uploads/');
//upload file
$config['upload_path'] = './uploads/';
$config['allowed_types'] = '*';
$config['max_filename'] = '255';
$config['encrypt_name'] = FALSE;
$config['max_size'] = '50000';
$config['overwrite'] = TRUE;
$this->load->library('upload', $config);
if (isset($_FILES['file']['name'])) {
if (0 < $_FILES['file']['error']) {
echo 'Error durante la carga' . $_FILES['file']['error'];
} else {
if (file_exists('./uploads/' . $_FILES['file']['name'])) {
echo 'Nombre de archivo ya existe : uploads/' . $_FILES['file']['name'];
} else {
$this->load->library('upload', $config);
if (!$this->upload->do_upload('file')) {
echo $this->upload->display_errors();
} else {
echo 'Archivo cargado! : ./uploads/' . $_FILES['file']['name'];
}
}
}
} else {
echo 'Porfavor selecciona un archivo';
}
}
Part of sendMail function:
$archivo = $_FILES['file']['name'];
$path = set_realpath('./uploads/');
$adjunto = $path.$archivo;
$this->email->attach($adjunto);
Part of the view and JS
<input type="file" id="file" name="file" />
$(document).ready(function (e) {
$('#file').on('change', function () {
var file_data = $('#file').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
$.ajax({
url: 'http://mail.mayordomus.cl/Cpersona/upload_file',
dataType: 'text',
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function (response) {
$('#msg').html(response);
},
error: function (response) {
$('#msg').html(response);
}
});
});
});

You can remove space characters from file name at client side using File constructor
let files = [new File([1], "file name.txt"), new File([2], "file name1.txt")];
let fd = new FormData();
for (let i = 0; i < files.length; i++) {
console.log(`Original file name: ${files[i].name}`);
let filename = files[i].name.replace(/\s/g, "-");
let file = new File([files[i].slice()], filename);
fd.append("files-" + i, file);
}
for (let [, prop] of fd) {
console.log(`FormData file name:${prop.name}`);
}

Related

Cloud Convert job error "started too many jobs at once"

I'm sending files to a php script from an html form. In the php script, I'm getting the temp file location and trying to convert it from a jpg to png. I'm getting this error from the server when trying to convert the file:
CloudConvert\Exceptions\HttpClientException: You have started too many
jobs at once in
C:\xampp\htdocs\photocloud\vendor\cloudconvert\cloudconvert-php\src\Exceptions\HttpClientException
upload.php:
require 'vendor/autoload.php';
use \CloudConvert\CloudConvert;
use \CloudConvert\Models\Job;
use \CloudConvert\Models\ImportUploadTask;
use \CloudConvert\Models\Task;
$obj_temp = $_FILES['file']['tmp_name'];
$obj_name = $_FILES['file']['name'];
$obj_errors = $_FILES['file']['error'];
$obj_checksum = md5_file($obj_temp, false);
$obj_size = filesize($obj_temp);
$obj_extention = strtolower(pathinfo($obj_name, PATHINFO_EXTENSION));
$cloudconvert = new CloudConvert([
'api_key' => 'my_key_here',
'sandbox' => false
]);
$obj_key = $obj_checksum.'.'.$obj_extention;
$job = (new Job())
->addTask(new Task('import/upload','upload-my-file'))
->addTask(
(new Task('convert', 'convert-my-file'))
->set('input', 'upload-my-file')
->set('output_format', 'png')
)
->addTask(
(new Task('export/url', 'export-my-file'))
->set('input', 'convert-my-file')
);
$cloudconvert->jobs()->create($job);
$url_task = $job->getTasks()->whereName('export-my-file')[0];
$cloudconvert->tasks()->upload($url_task, fopen($obj_temp, 'r'), 'test.png');
$cloudconvert->jobs()->wait($job);
foreach ($job->getExportUrls() as $file) {
echo $file->url;
}
upload.js
var fileInput = document.querySelector('.upload');
$.each(fileInput.files, function(index, val) {
formData = new FormData();
formData.append('file', fileInput.files[index]);
$.ajax({
type: 'POST',
url: 'upload.php',
processData: false,
contentType: false,
data: formData,
success: function(response) {
console.log(response);
}
});
});

Unable to download file in laravel ajax on button click

When I am trying to use the download button to download file in laravel ajax, it is not working properly and I am not able to download file.
Below is my code:
<button type="button" request_id="'.$data->id.'" class="btn btn-success download_request_btn" > Download </button>';
Controller:
public function downloadReport(Request $request)
{
$request_id = $request->request_id;
$downloadReport = Upload::where('id', $request_id)->first();
$upload_report = $downloadReport->upload_report;
$headers = array(
'Content-Type: application/pdf',
'Content-Type: application/docx',
);
$url= url('storage/documents/request/'. $upload_report);
return response()->download($url);
}
Ajax:
$(document).on('click', '.download_request_btn', function(){
var request_id = $(this).attr('request_id');
console.log(request_id);
var formData = new FormData();
formData.append('request_id',request_id);
jQuery.ajax({
type: "post",
url: site_url+"/DownloadAjax",
data: formData,
contentType:false,
processData:false,
success: function (res) {
}
});
});
Just to pseudo-code it up with trusting your data is coming back as desired I think you need to trigger the download in your success callback with a variation of the following (may need to adjust to your need):
$(document).on('click', '.download_request_btn', function(){
var request_id = $(this).attr('request_id');
console.log(request_id);
var formData = new FormData();
formData.append('request_id',request_id);
jQuery.ajax({
type: "post",
url: site_url+"/DownloadAjax",
data: formData,
contentType:false,
processData:false,
success: function (res) {
const data = res;
const link = document.createElement('a');
link.setAttribute('href', data);
link.setAttribute('download', 'yourfilename.extensionType'); // Need to modify filename ...
link.click();
}
});
});
you can pass header to force file type and download
$file_path = storage_path('documents/request/'. $upload_report);
$headers = array('Content-Type'=> 'application/pdf');
return \Response::download($file_path, 'file.pdf', $headers);
here you need to add header based on your file type
ref link https://laravel.com/docs/8.x/responses#file-downloads
if(!empty($fileName) && file_exists(($exportDir.'/'.$fileName))) {
$data = route('yourdownloadCSV',['nameFile' => $fileName]);
}
return response()->json([
'status' => 1,
'data' => $data,
'message'=> trans('messages.item_upload_shop_ok'),
]);
public function yourdownloadCSV($nameFile) {
ini_set('memory_limit', '9072M');
ini_set('MAX_EXECUTION_TIME', '-1');
set_time_limit(10*60);
$fullFolderZipFile = public_path().'/export/'.date('ym');
$filePath = $fullFolderZipFile.'/'.$nameFile;
$nameDownload = "test";
if(file_exists($filePath)) {
$byteS = filesize($filePath);
$mb = number_format($byteS / 1048576, 2) ;
if($mb>10){
$filePathZip= ZipUtil::generateZipFromFile($filePath,$fullFolderZipFile,$nameFile);
$nameDownload .=".zip";
}else{
$filePathZip = $filePath;
$nameDownload .=".".pathinfo($nameFile, PATHINFO_EXTENSION);
}
$mimeType = File::mimeType($filePathZip);
return response()->download($filePathZip,$nameDownload,[
'Content-Type' => $mimeType,
'Content-Encoding' => 'Shift-JIS'
])->deleteFileAfterSend(true);
}
return '';
}

ajax running error despite response being 200

I have multiple uploads on a page, and I am workin on tidying it up, so:
Here's my js:
$(".img").change(function () {
var form = $(this).closest('form');
getPath(form);
})
deleteButton();
copyGalleryData();
});
function getPath(form) {
var name = $(form).attr('name');
submitImage(form, name);
}
var path_to_delete;
function submitImage(form, name) {
var url = '/image/upload';
var form_data = new FormData($(form)[0]);
submit(name);
form_data.append('img', $(form).children(".img"));
$.ajax({
url: url,
data: form_data,
dataType: 'json',
async: true,
type: 'post',
processData: false,
contentType: false,
success: function (data) {
console.log(data);
$(form).children('.image-container').append('<img id="image" name=' + name + '" src="' + data + '" />')
$(".imageDelete").attr('data', data);
alerts();
var deleting = false;
success(name, deleting, data);
$('.messages').html('<div class="alert alert-success">Image Uploaded!<div>');
},
error: function (data) {
alerts();
fail();
$('.messages').html('<div class="alert alert-danger">File type not supported! Use files with image extension only!</div>');
},
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
}
and controller:
class ImageController extends Controller
{
use S3;
public function upload(ImgRequest $request)
{
if ($request->hasFile('img')) {
$this->imageEntity();
return response()->json($path);
}
if ($request->hasFile('coverUpload')) {
$this->imageCover();
}
}
public function imageEntity()
{
$s3Path = config('app.path', public_path());
$image = Input::file('img');
Log::info('Retrieving Image', ['image' => $image]);
$filePath = 'public/logo/' . time() . '.' . $image->getClientOriginalExtension();
$path = $s3Path . $filePath;
$this->S3Store($filePath, $image);
$session = session()->get('key');
try {
$update_image = Entity::find($session);
$update_image->logo = $path;
$update_image->save();
Log::info('Succesfully saved logo for', ['entity_id' => $session]);
return response()->json($path);
} catch (Exception $e) {
Log::error('Images:', ['message' =>$e->getMessage(), 'entity_id' => $session]);
}
}
public function imageCover()
{
$s3Path = config('app.path', public_path());
$image = Input::file('coverUpload');
Log::info('Retrieving Cover', ['image' => $image]);
$filePath = 'public/cover/' . time() . '.' . $image->getClientOriginalExtension();
$path = $s3Path . $filePath;
$this->S3Store($filePath, $image);
$session = session()->get('key');
try {
$image = new Images;
$image->path = $path;
$image->cover = true;
$image->entity_id = $session;
$image->save();
Log::info('Succesfully saved logo for', ['entity_id' => $session]);
return $path;
} catch (Exception $e) {
Log::error('Images:', ['message' =>$e->getMessage(), 'entity_id' => $session]);
}
}
Now the funny thing is response is 200, however it is empty ($path is defined) and ajax is triggering error: part of the code and not success. I have checked the log, and try has been successful:
[2017-10-16 11:22:01] local.INFO: Retrieving Image {"image":"[object]
(Illuminate\Http\UploadedFile: /tmp/phpHPchM4)"} [2017-10-16
11:22:01] local.INFO: Adding to S3 [2017-10-16 11:22:05] local.INFO:
Succesfully added to S3 [2017-10-16 11:22:05] local.INFO:
Succesfully saved logo for {"entity_id":"324"}
Could anyone please help me solve this matter?
Update::
I have updated the controller so that the function returns $path, and main function return the response, however for some reason it is saying that $path is undefined, how to pass data from return to controller that is returned it?

how can i use post and files with ajax?

i'd like to know how can i use $_POST and $_FILES using ajax, i'm trying to upload an image and insert a value on my database with post.
i've tried but it doesn't work.
index.html
<div class="form-group">
<label> img </label>
<input type="file" name="img" id="img" />
<input type='hidden' id='value' value='<?=$_GET["p"]?>' />
</div>
ajax.js
$(document).ready(function() {
$('#upload').click(function() {
var value = $('#value').val();
var img = $('#img').val();
var string= 'value=' + value + '&img=' + img;
$.ajax({
type: "POST",
url: "ajax.php",
data: string,
dataType: "json",
success: function(data) {
var success = data['success'];
if (success == true) {
console.log('success');
} else {
console.log('error');
}
}
});
return false;
});
});
ajax.php
<?php
if(isset($_POST["value"]) && isset($_FILES["img"])) {
echo json_encode(array("success" => true));
} else {
echo json_encode(array("success" => false));
}
?>
The best approach is convert image to base64 first. This conversion is done in the change listener.
var files = [];
$("input[type=file]").change(function(event) {
$.each(event.target.files, function(index, file) {
var reader = new FileReader();
reader.onload = function(event) {
object = {};
object.filename = file.name;
object.data = event.target.result;
files.push(object);
};
reader.readAsDataURL(file);
});
});
$("form").submit(function(form) {
$.each(files, function(index, file) {
$.ajax({url: "/ajax-upload",
type: 'POST',
data: {filename: file.filename, data: file.data},
success: function(data, status, xhr) {}
});
});
files = [];
form.preventDefault();
});

Image not getting posted with ajax(without submitting the form)

My form is -
<form id="fileupload" method="post" enctype="multipart/form-data">
<input type="file" id="headerimage" spellcheck="true" class="typography" name="headerimage">
</form>
My ajax code is -
var fileData = new FormData($('#fileupload'));
fileData.append('imagefile', $('#headerimage')[0].files);
$.ajax({
type : 'post',
data : fileData,
url : 'UploadImage.php',
dataType: 'json',
processData: false,
success : function(data)
{
alert("done");
},
});
Php code -
<?php
# Data Base Connection
require_once('conn/dbConn.php');
var_dump($_REQUEST);
if (!empty($_FILES)) {
var_dump($_FILES);
}
Please Help. On the php page i am not getting file data.
HTML CODE:
<form id="fileupload" method="post" enctype="multipart/form-data">
<input name="userImage" id="uploadForm" type="file" class="inputFile" />
</form>
AJAX :
<script type="text/javascript">
$(document).ready(function (e){
$("#fileupload").on('submit',(function(e){
e.preventDefault();
$.ajax({
url: "UploadImage.php",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
success: function(data){
$("#targetLayer").html(data);
},
error: function(){}
});
}));
});
</script>
Use this javascript
$(document).on("submit", "#fileupload", function(event)
{
event.preventDefault();
$.ajax({
url: 'UploadImage.php',
type: 'POST',
data: new FormData(this),
dataType: 'json',
processData: false,
contentType: false,
success: function (data, status)
{
}
});
});
Try this...
//Image will upload without submit form
<form id="uploadimage" action="" method="post" enctype="multipart/form-data">
<div id="image_preview"><img id="previewing" src="noimage.png" /></div>
<hr id="line">
<div id="selectImage">
<label>Select Your Image</label><br/>
<input type="file" name="file" id="file" required />
</div>
</form>
<script>
$(document).ready(function (e) {
$("#uploadimage").on('change',(function(e) {
e.preventDefault();
$.ajax({
url: "UploadImage.php", // Url to which the request is send
type: "POST", // Type of request to be send, called as method
data: new FormData(this), // Data sent to server, a set of key/value pairs (i.e. form fields and values)
contentType: false, // The content type used when sending data to the server.
cache: false, // To unable request pages to be cached
processData:false, // To send DOMDocument or non processed data file it is set to false
success: function(data) // A function to be called if request succeeds
{
}
});
}));
});
</script>
UploadImage.php
<?php
if(isset($_FILES["file"]["type"]))
{
$validextensions = array("jpeg", "jpg", "png");
$temporary = explode(".", $_FILES["file"]["name"]);
$file_extension = end($temporary);
if ((($_FILES["file"]["type"] == "image/png") || ($_FILES["file"]["type"] == "image/jpg") || ($_FILES["file"]["type"] == "image/jpeg")
) && ($_FILES["file"]["size"] < 100000)//Approx. 100kb files can be uploaded.
&& in_array($file_extension, $validextensions)) {
if ($_FILES["file"]["error"] > 0)
{
echo "Return Code: " . $_FILES["file"]["error"] . "<br/><br/>";
}
else
{
if (file_exists("upload/" . $_FILES["file"]["name"])) {
echo $_FILES["file"]["name"] . " <span id='invalid'><b>already exists.</b></span> ";
}
else
{
$sourcePath = $_FILES['file']['tmp_name']; // Storing source path of the file in a variable
$targetPath = "upload/".$_FILES['file']['name']; // Target path where file is to be stored
move_uploaded_file($sourcePath,$targetPath) ; // Moving Uploaded file
}
}
}
else
{
echo "<span id='invalid'>***Invalid file Size or Type***<span>";
}
}
?>
JS code -
var form = document.getElementById('fileupload');
var fileInput = document.getElementById('headerimage');
var file = fileInput.files[0];
var formData = new FormData();
var filename = '';
formData.append('file', file);
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
filaname = xhr.responseText;
}
}
// Add any event handlers here...
xhr.open('POST', form.getAttribute('action'), true);
xhr.send(formData);
PHP code -
<?php
# Data Base Connection
require_once('conn/dbConn.php');
if (!empty($_FILES)) {
$file = $_FILES;
if ($file['file']['error'] == 0) {
$name = explode('.', $file['file']['name']);
$newName = "header.".$name[count($name)-1];
if (move_uploaded_file($file['file']['tmp_name'], "../assets/Themes/Default/".$newName)) {
echo $newName;
exit;
}
} else {
echo "";
exit;
}
} else {
echo "";
exit;
}

Categories