How to upload files from a plugin to wordpress media library? - html

I need to developed a front-end drag and drop plug in. First I collect the html5 drag and droping code.
Download the source code in zip format - https://github.com/Mashpy/html5-drag-and-drop-upload/archive/master.zip
Put the files in localhost and open. If you upload files it will be uploades in "uploads" folder. Because I put code in " /js/mashpy.js " that this time "upload.php" file will be loaded and it will send the files in "uploads" folder.
That means this process work something like this -
index.html -- js/mashpy.js -- upload.php -- send file to "uploads" -- dump.php will show the result that upload successfully.
Now I have to developed a front-end drag and drop plug in. But I don't know how to upload files in wordpress media library. In this source code upload.php works which send files to "uploads" folder. But what happened in wordpress? How to send files to wordpress media library?

You can't simply upload files to wp-content/uploads/. They won't show up in Media Library. You need to use WordPress function media_handle_upload($file,$post_id), passing 0 as post ID (so, it's not attached to any post/page).
Something like:
if ($_FILES) {
foreach ($_FILES as $file => $array) {
if ($_FILES[$file]['error'] !== UPLOAD_ERR_OK) {
return "upload error : " . $_FILES[$file]['error'];
}
$attach_id = media_handle_upload( $file, 0 );
}
}
You can study this plugin to see how it does it: Add From Server. And also research in WordPress Answers for examples of this function usage.

Related

Import files into a directory on a HTML document

I am wondering if I can have a webpage where I can tell it to grab my file and put it in a directory, such as: "http://example.ex/folder". Meaning the file I provided is put into the "folder" folder.
Overall process:
Button says: "Import file"
I select a file, and my file is "text.txt"
It takes my file "text.txt" and adds it to the local system/directory of the website.
You can do this using JQuery File Upload and then adding a backend service that captures the file and saves it.
For example, here is a repository that has a basic Python (Flask) server integrated with JQuery File Upload that will take an uploaded file and place it on the server:
https://github.com/ngoduykhanh/flask-file-uploader
I'd put the rest of the code here, but it is a lot - and requires HTML, JavaScript and a back-end language (like Python).
Here is the documentation on JQuery File Upload: https://github.com/blueimp/jQuery-File-Upload
As a word of caution, DO NOT TRUST ANYTHING UPLOADED TO YOUR SERVER. Meaning, do not put it out on the open internet without some sort of authentication or checks in place to make sure only files you intend are uploaded. Otherwise, people will find it and upload scripts turning your device into a Bitcoin miner, spam relay, or bot host.
Instead of doing it this way, why not use SFTP to upload it to your server to host? At least that way you can lock down access.

Create download link for static asset file

I would like to put a download link on my website so the users can download the file template.csv. The file is static and is located at the root of my /grails-app/assets folder.
Inside my page.gsp, I have tried 2 methods do so, to no avail :
Download the template
this results in a template.csv file being downloaded, but the content is the html code of page.gsp rather than the original content of the file I uploaded in my assets.
Download the template
the generated html file has a link to localhost:8080/mysite/assets/template.csv but clicking it prompts an error message : Failed - no file.
What is the correct way to do what I want to achieve ? Is there an issue with extra permissions I would need to add to allow the download of my file ?
Our webapp relies on a rather old technological stack :
Grails 2.3.4
Plugin asset-pipeline-2.2.5
I have had some troubles with downloading files straight with a -tag.
To overcome this, I use Controller method to return the file and place the downloadable files in their own folder under web-app/:
class MyController {
#Autowired()
AssetResourceLocator assetResourceLocator
def downloadExcelTemplate () {
String fileName = "MyExcelFile.xlsx"
/* Note: these files are found in /web-app/downloadable directory */
Resource resource = assetResourceLocator.findResourceForURI("/downloadable/$fileName")
response.setHeader "Content-disposition", "attachment; filename=${resource.filename}"
response.contentType = 'application/vnd.ms-excel'
response.outputStream << resource.inputStream.bytes
}
}
And just use regular a-tag to to link to this controller method.
This way you also gain more control over file downloads.

Playframework: Assets are not updated in production mode when changed

I created a mobile html5 web with the playframework 2.x. Users are able to upload images via the app, which then are stored on the server the app is running on.
Images are stored in public/imagesand acessed like this: #routes.Assets.at(images/images1.jpg)
My problem is that whenever a user is uploading an image to my server and then is trying to view the uploaded image afterwards, the image can`t be displayed.
I found out that whenever I restart the play process on the server, then the newly uploaded image will be displayed correctly. I normally start my production server like this:
activator dist
and afterwards unzip the created zip directory and run the generated script.
I figured that the problem is that when the app is packed it will only pack the assets available at the time in the assets.jar and therefore not be able to show new images which are added after the server is started.
So my question is, what do I need to change so that images, which are changed or added while the server is running are displayed correctly, without having to repack and restart the app.
My routes file
# Routes
# This file defines all application routes (Higher priority routes first)
# ~~~~
# Home page
GET / controllers.Application.index
# Used in Javascript to push new User into Database via Ajax
PUT /users/:i controllers.Userdata.addUser(i: Int)
... similiar PUT Requests ...
PUT /deactUser/:i controllers.Userdata.deactUser(i: Int)
GET /reloadUsers controllers.Userdata.reloadUsers(minA: Int, maxA: Int, gend: String, orient: String, verf: String)
GET /ads controllers.Application.getAds()
# Javascript Router
GET /assets/javascripts/routes controllers.Application.javascriptRoutes()
# Map static resources from the /public folder to the /assets URL path
GET /assets/*file controllers.Assets.at(path="/public", file)
After creating dist package the public folder is accessed from created *.jar file, therefore you need to re-dist your app to make uploaded files available in it.
Instead you should create some directory in filesystem and define its path (preferably via configuration file), so you will upload files and serve them into/from independent location. Of course you'll need to write custom action to serve them as well, but that's just several lines of code.
Here's what to implement in practise:
In your routes file, add something like this:
GET /customImage/:name controllers.Application.imageAt(name:String)
Then implement imageAt like this:
public Result imageAt(String imageName) throws FileNotFoundException {
File imageFile = new File("/path/to/image"+imageName);
if (imageFile.exists()) {
String resourceType = "image+"+imageName.substring(imageName.length()-3);
return ok(new FileInputStream(imageFile)).as(resourceType);
} else {
return notFound(imageFile.getAbsoluteFile());
}
}
And that's it. Anything you put to "/path/to/image" will be accessible via url /customerImage/
They can also be accessible via revert routes like #routes.Application.imageAt(imageName)

Referring to a file with partially known name in html

I am making a webpage. I have to give link of a log file which is present on the server but that file is generated with a random number at the end.
I know the starting part of the filename. Here is my code -
Download log file Here
for example the name of the file is "log_parser2088.log" this 2088 number is randomly generated everytime the code runs and there is only one file in that folder which starts with the name "log_parser". I want to give reference to this file but this is not working.
HTML doesn't support this kind of references. Use PHP or ASP.NET for this task since these server side programms have access to the servers file system and can, f.e., read every filename in a directory.
Example for PHP:
// path to your log file directory
$directoryPath = "\\home\\logs\\";
// read all files from that directory
$files = scandir($directoryPath);
// print download link
foreach($path in $files)
echo("Download");

PHP File uploader. Cannot upload file to a folder

I made a PHP file uploader and I need to upload a file in a specific page of a webpage. I use Dreamweaver CS3 to make my websites and PHP files.
But there is a catch, my Manager doesn't know how to upload his Policies in a specific webpage. All policies are in PDF format. For that he wants me to make a PHP File Uploader to upload his files in front hand, for Example: There is a new policy which needs to be uploaded in a specific he/she would need to click on the choose file button, upload and choose the file, rename the following file and upload it in the webpage with ease.
It is easy to upload the Policies using Dreamweaver but my manager doesn't know how to upload files using that kind of method.
I need to make a php uploader, So i can upload my policies and post it in a specific page. How do you create a code for that.
EDIT
I have a html file by the name of uploads.html:
<form action="index1.php" method="post" enctype="multipart/form-data">
<input type="file" name="file" id="file"><br><br>
<input type="submit" value="submit" name="submit">
</form>
and This is the php code (index1.php):
<?php
if(isset($_POST['submit'])){
$name = $_FILES['file']['name'];
$temp_name = $_FILES['file']['tmp_name'];
if(isset($name)){
if(!empty($name)){
$location = '../uploads/';
if(move_uploaded_file($temp_name, $location.$name)){
echo 'uploaded';
}
}
} else {
echo 'please uploaded';
}
}
?>
EDIT
The code for this uploader is for upload file in a specific folder, I need to upload my policies in a specific Webpage or any website. How can I create a code for this? I am sorry but I am new to PHP
I dont have enough reputation to post images so I will just insert the error statements here.
There are the following errors in my php file:
Warning: move_uploaded_file(../uploads/apache_pb2.gif): failed to open stream: No such file or directory in C:\xampp\htdocs\index1.php on line 8
Warning: move_uploaded_file(): Unable to move 'C:\xampp\tmp\phpB959.tmp' to '../uploads/apache_pb2.gif' in C:\xampp\htdocs\index1.php on line 8
You are using a wrong function to perform upload operation.
Here you can find an answer to your problem:
http://php.net/manual/en/function.move-uploaded-file.php
There is an example of uploading a file. You can find more info in the users comments
Replace below line
copy( $_FILES['file']['name'], "/var/www/html" ) or
with
move_uploaded_file( $_FILES['file']['tmp_name'], "/var/www/html" ) or
$_FILES["file"]["tmp_name"] - the name of the temporary copy of the
file stored on the server
so You have to change Your code
move_uploaded_file( $_FILES['file']['tmp_name'], "/var/www/html/".$_FILES['file']['name'] )
$target_dir = $_SERVER['DOCUMENT_ROOT'] . URL_SUB_FOLDER . "/file/";
// move to folder file
$file = basename($_FILES["file"]["name"]);
$target_file0 = $target_dir . $file;
if(move_uploaded_file($_FILES["file"]["tmp_name"], $target_file0)){
// do something.
}