Blueimp jQuery File Upload - how to change upload directory - file-upload

how can i change the upload directory?
i want to change the file upload directory dynamically
f.g : for each user,upload files to her/his folder
thanks

You can store the directory in a $_SESSION variable or in a $_COOKIE , and then get the saved value in the file /php/index.php
$uplDir = $_SESSION["uploadDirectory"].'/;
$option = array(
/* some options */
'upload_dir' => $uplDir,
/* .... */
);
$upload_handler = new UploadHandler($option);
ps. remember the session_start(); at the beginning

You can send that via parameters in the form data in js file
<script>
$(function () {
$('#fileupload').fileupload({
dataType: 'json',
formData: [{ name: 'custom_dir', value: '/save/file/here/' }],
done: function (e, data) {
$.each(data.result.files, function (index, file) {
$('<p/>').text(file.name).appendTo(document.body);
});
}
});
});
</script>
//=========================
while in the upload handler definition
require('UploadHandler.php');
$custom_dir = $_SERVER['DOCUMENT_ROOT'] . $_REQUEST['custom_dir'];
$upload_handler = new UploadHandler(array('upload_dir' => $custom_dir));

Related

Updating the image in laravel 8 + inertia, validation error even the fields are filled

I'm working with Laravel 8 + inertiajs. I can create a product with or without an image. But when I try to update a product and upload a new image, the validation looks for the required field even they're already filled.
here is my input field:
<input name="images" type="file" #input="form.images = $event.target.files[0]" />
in my vue:
props: {
product: Object,
categories: Array
},
data() {
return {
form: this.$inertia.form({
name: this.product.name,
category_id: this.product.category_id,
description: this.product.description,
date: this.product.date,
images: this.product.images
})
}
},
methods: {
update() {
this.form.put(this.route('products.update', this.product.id, {
preserveState: true
}))
},
}
})
my update controller:
public function update(UpdateProductRequest $request, Product $product)
{
$inputs = $request->validated();
if ($request->hasFile('images')) {
$filename = $request->images->getClientOriginalName();
$file = $request->images->storeAs(('images'), $filename);
$product->images = $file;
$inputs['images'] = $product->images;
}
$product->name = $inputs['name'];
$product->category_id = $inputs['category_id'];
$product->description = $inputs['description'];
$product->date = $inputs['date'];
$product->update();
session()->flash('flash.banner', 'Product Updated Successfuly');
session()->flash('flash.bannerStyle', 'success');
return redirect()->route('products.index');
}
multipart/form-data request is not natively supported in some languages for the put,patch or delete methods. The workaround here is to simply upload files using post instead.
Some frameworks, such as Laravel and Rails, support form method spoofing, which allows you to upload the files using post, but have the framework handle the request as a put or patch request. This is done by including a _method attribute in the data of your request.
Inertia.post(`/users/${user.id}`, {
_method: 'put',
avatar: form.avatar,
})

Upload Textarea Content as a file

I want to upload the content of a textarea as a file because content exceed max_input_vars limit in php.ini. In the future maybe it will increase so I prefer to upload it as a file ^^
I show the content to the user in a textarea, so it is editable :) And then click "Save" and send the content of the textarea as a file. How can I do ?
<span onclick="data_save();">Save</span>
<textarea id="textarea">
<?php
print_r($tab);
?>
</textarea>
<script type="text/javascript">
<?php
echo file_get_contents('/var/www/'.$jsdir.'/jquery-2.1.4.min.js');
?>
function data_save()
{
var textToWrite = document.getElementById("textarea").innerHTML;
var textFileAsBlob = new Blob([ textToWrite ], { type: 'text/plain' });
var fileNameToSaveAs = "ecc.plist";
var downloadLink = document.createElement("a");
downloadLink.download = fileNameToSaveAs;
downloadLink.innerHTML = "Download File";
if (window.webkitURL != null)
{
// Chrome allows the link to be clicked without actually adding it to the DOM.
downloadLink.href = window.webkitURL.createObjectURL(textFileAsBlob);
} else {
// Firefox requires the link to be added to the DOM before it can be clicked.
downloadLink.href = window.URL.createObjectURL(textFileAsBlob);
downloadLink.onclick = destroyClickedElement;
downloadLink.style.display = "none";
document.body.appendChild(downloadLink);
}
// downloadLink.click();
$.ajax({
url: 'data_save.php',
data: data,
type: 'POST',
success: function(retour)
{
if (retour.indexOf('Oups') != -1)
alert(retour);
},
error: function(obj, text, error)
{
alert("Oups.. " + obj.responseText);
}
});
}
</script>```
It not possible, user must download and the upload the file by himself....

How to preview files before uploaded to server by using file-upload component of vue.js & element-ui?

I'm using vue.js & element-ui to upload files and preview files. I want to preview file(.pdf/.docx/.jpg...) before uploaded to server.
<el-upload
ref="uploadFile"
:on-change="onUploadChange"
:on-preview="handlePreview"
:on-remove="handleRemove"
:before-remove="beforeRemove"
:file-list="fileList"
:http-request="handleUpload"
:data="extendData"
:auto-upload="false"
class="upload-demo"
drag
action="uploadUrl"
multiple>
<i class="el-icon-upload"/>
<div class="el-upload__text">drag here, or <em>click to upload</em></div>
</el-upload>
Only the on-change function can get the content of the file, while the on-preview function only get the meta message. How to get the file content and preview that before which is uploaded to server?
It's not the meta, it's the file. So you need to use a FileReader on the file:
handlePreview(file) {
const reader = new FileReader()
reader.onload = e => console.log(e.target.result) // here is the result you can work with.
reader.readAsText(file)
}
I am also using Element-UI upload box, the following code allow user to import a JSON file to Vue, and preview its content in a new window when clicking the file name. The file is read and stored as object in data during on-change, then
Vue component:
<el-upload class="upload-box" drag action="" :auto-upload="false" :on-change="handleImport" :on-preview="handlePreview" :limit="1" :on-exceed="handleExceed">
<i class="el-icon-upload"></i>
<div class="el-upload__text">Drop file here or <em>click to upload</em></div>
<div class="el-upload__tip" slot="tip">Single JSON file with size less than 500kb</div>
</el-upload>
Script:
export default {
data() {
return {
uploadFile: null,
fileContent: null,
}
},
methods: {
handleImport(file) {
this.uploadFile = file
let reader = new FileReader()
reader.readAsText(this.uploadFile.raw)
reader.onload = async (e) => {
try {
this.fileContent = JSON.parse(e.target.result)
} catch (err) {
console.log(`Load JSON file error: ${err.message}`)
}
}
},
handlePreview() {
let myWindow = window.open();
myWindow.document.write(JSON.stringify(this.fileContent));
myWindow.document.close();
},
handleExceed(files, fileList) {
this.$message.warning(`The limit is 1, you selected ${files.length + fileList.length} totally, please first remove the unwanted file`);
},
},
}

how to access $_FILES parameters while trying to do File Upload without Form?

I have written a functionality where I want to upload a form without using any forms whatsoever, I am calling an ajax event on change event of input type=file with id, I am getting the $_FILES data in ajax file 'upload.php' using POST method using jQuery. The input tag is not inside any form tag. It stands individually. Below is my code:
my plain html input type='file' without form:
<div class="profile_pic">
<img id="upload-button" class="profile-pic img-circle profile_img" src="img/default-image.png" alt="default">
<input class="file-upload" type="file" name="profile_pic" id="profile_pic" />
</div>
My Javascript code is:
var readURL = function(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#upload-button').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
$(".file-upload").on('change', function(){
readURL(this);
alert('working');
var file = profile_pic.files[0];
var formData = new FormData();
formData.append('formData', file);
$.ajax({
url: "uploadFile.php",
type: "POST",
processData: false,
contentType: false,
dataType : 'json',
data: formData,
success: function (data) {
alert(data);
}
});
});
$("#upload-button").on('click', function() {
$(".file-upload").click();
});
UploadFile.php code below:
<?php
print_r($_FILES);
?>
the following file data Am getting in alert :
Array
(
[formData] => Array
(
[name]=> Tulips.jpg
[type]=> image/jpeg
[tmp_name]=> chroot/tmp/phpipdF97
[error]=> 0
[size]=> 620888
)
)
how can I access those file data inorder to upload file to a destination folder path using php's move_uploaded_file()? Thanks in advance.
I got the solution. I have accessed the $_FILES values in "uploadFile.php" like below:
$_FILES["formData"]["tmp_name"]
$_FILES["formData"]["name"]

Upload html file to Tinymce read content and set content of editor

I will implement a function that display a file browser where i can upload a html file to read the html documents content and than past this content to editor.
How can i set a toolbar button that opens a file browser, that allows only html file uploads with max file size of 2MB.
Can i read content of file without to save it, like file_get_contents() on php.
I created my own TinyMCE plugin for that.
If you don't know how plugins work, create a new folder named htmlFileImport under the TinyMCE plugins directory. If you are calling tinymce.min.js, then inside this folder create a file named plugin.min.js, otherwise name it plugin.js then paste this code inside
tinymce.PluginManager.add('htmlFileImport', function(editor, url) {
editor.addButton('htmlFileImport', {
text: "Import HTML File",
icon: false,
onclick: function() {
if(editor.getContent() == ""){
editor.showFileDialog();
}
else{
editor.showReplaceContentConfirmDialog();
}
}
});
editor.showReplaceContentConfirmDialog = function(){
eval(editor.dialogConfirmReplaceContentId).Open();
eval(editor.dialogConfirmReplaceContentId).setzIndex(101);
}
editor.showInvalidHtmlFileDialod = function(){
eval(editor.dialogInvalidHtmlFileId).Open();
eval(editor.dialogInvalidHtmlFileId).setzIndex(101);
}
editor.showFileDialog = function(){
var fileSelector = document.createElement('input');
fileSelector.setAttribute('type', 'file');
fileSelector.style.display = 'none';
fileSelector.onchange = function(e) {
var file = fileSelector.files[0];
if (file) {
var reader = new FileReader();
reader.readAsText(file, "UTF-8");
reader.onload = function (event) {
var bodyHtml = event.target.result;
var bodyOpen = bodyHtml.indexOf('<body');
if(bodyOpen == -1)
bodyOpen = bodyHtml.indexOf('< body');
var bodyClose = bodyHtml.indexOf('</body>') + 6;
if(bodyClose == -1)
bodyClose = bodyHtml.indexOf('</ body>') + 7;
if(bodyOpen != -1 && bodyClose != -1){
bodyHtml = bodyHtml.substring(bodyOpen, bodyClose);
var divHtml = document.createElement('div');
divHtml.style.display = 'none';
divHtml.innerHTML = bodyHtml;
editor.setContent(divHtml.innerHTML);
}
else{
editor.showInvalidHtmlFileDialod();
}
}
reader.onerror = function (evt) {
editor.showInvalidHtmlFileDialod();
}
}
};
fileSelector.click();
}
});
dialogConfirmReplaceContentId and dialogInvalidHtmlFileId are custom properties I previously added to my editor in the init function, you will certainly have your own mechanism, but I let this code so you can understand what's going on.
Then to include this new plugin, just add it during your editor's creation by adding the configuration like this:
tinymce.init({
plugins: [
'yourOtherPlugins htmlFileImport'
],
toolbar1: 'yourOtherPlugins htmlFileImport',
.....
});
For allowing only HTML file, you have no way to ensure the user will import this file's type. You can check if file name's extension is .html or .htm or you can do like I did: if I can't find any <body> tag inside then I consider this is not a valid HTML.
You can check the file size by simply calling file.size
You are new on StackOverflow so just to tell you that when you ask a question, you have to show that you tried something and did some research before posting. Here we don't post like if it was a simple Google search. We post question when we are stuck, after trying.