how to request a single file as object - javascript

I just start to learn javascirpt, php about 2 days. The problem I face is I already have a x.dcm file under server root, and I already known that path(e.g. http://localhost:8888/....)
My question is how can I simply grab that file from server to use, maybe something like:
var file= 'http://localhost:8888/....'; ////file is not an object
I ask this question because I already known how to use input method:
<input type="file" name="file" id="file">
<script>
$('#file').on('change',function(e){
var file = e.target.file; ///file is an object
});
</script>
but that is not what I want, what I want is to use an existed file rather than input.
So the whole thing is that:
<form id="input" method="post" enctype="multipart/form-data">
<input type="file" id="fileToUpload" name="fileToUpload">
</form>
I firstly make a input to upload some file,then in script
<script>
$("form#input").submit(function(){
var formData = new FormData($(this)[0]);
$.ajax({
url: 'segmentation.php',
type: 'POST',
data: formData,
async: false,
success: function (html) {
$('#segbound').html(html);
},
cache: false,
contentType: false,
processData: false
});
return false;
});
</script>
I sent this file(e.g image.dcm) to do something( run a exec) on the server side, then it generates another image(imgproc.dcm) in an expected path(http://localhost:8888/....), and then the next thing is that I what that processed image display on the screen. To do that I need to use a js called cornerstone, and the function in it imageLoader.fileManager.get(file)
which file is that one I what to display.
When I select from input using var file = e.target.file; as I mentioned above, it works perfect, then I check the file type it is a [file object].
But when I want to simply display that 'imgproc.dcm' by using var file= 'http://localhost:8888/....'; the file type is not an object which comes out my question, how can I simply grab that known path image to use as an object.
Or, to improve that, it is possible to get the return (generated imgproc.dcm) directly after it process on server side, and then to use that return(maybe give it an id...do not know) to display (call cornerstone function imageLoader.fileManager.get(file))
On server side, it looks like:
<?php
$target_dir = "/Applications/MAMP/htdocs/dicomread/temp/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
if (file_exists($target_file)) {
echo "file has already been uploaded.";
$uploadOk = 0;
}
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
} else {
if (move_uploaded_file($_FILES['fileToUpload']['tmp_name'], $target_file)) {
echo "The file ". basename( $_FILES['fileToUpload']['name']). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
$cmd = "/Applications/MAMP/htdocs/dicomread/abc 2>&1";
$Output_fileName = "imgproc.dcm";//$_FILES['fileToUpload']['name'];
exec("$cmd $target_file $Output_fileName);
echo "<br/>done";
?>
Any help would be appreciated.

Use fopen with URL to the file:
$file = fopen("http://localhost:8888/x.dcm", "r");
Refer to this for fopen: http://php.net/manual/en/function.fopen.php

Related

Jquery & Ajax -> File upload not possible

I got totally lost.
Ive tried to make some Image Upload function in PHP and everything works fine. Because i dont want the whole Page to reload, when uploading a File i wanted to use AJAX with Jquery, to send the Form Content (Image) via POST to a file like upload.php with an hidden ajax request.
No matter what i try its impossible to send anything with formData(). I copied & pasted several Sample Codes, tried changing the Code, nothing happens when i use formData().
A normal request with Jquery / Ajax, using POST works fine.
Here ist the Sample of my last used Code..
Could my XamPP has been misconfigured, or what could cause that really not one of the Scripts from google, tutorial pages etc works?
<!DOCTYPE html>
<html>
<body>
<script type="text/javascript" src="jquery.min.js"></script>
<form id="Test" action="" method="post" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
</form>
<button id="Knopf">Knopf</button>
<div id="Disp">fghfgh</div>
</body>
<script>
$(document).ready(function(){
$("#Knopf").click(function(){
var formData = new FormData(Test);
$.ajax({
url : "uploadtest2.php",
type : "POST",
data : formData,
cache : false,
contentType : false,
processType : false,
success : function() {
$("#Disp").html(result);
}
});
});
});
</script>
</html>
<?php
$target_dir = "Media/uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
}
// Check if file already exists
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
// Check file size
if ($_FILES["fileToUpload"]["size"] > 500000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
echo "The file ". htmlspecialchars( basename( $_FILES["fileToUpload"]["name"])). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
?>
The problem is this:
if(isset($_POST["submit"])) {
There's no element named submit in the form, so this check fails. Even if you had a submit button in the form, it wouldn't be included in formData, because buttons are only automatically included in POST data when they trigger normal form submission.
You can add that to formData.
var formData = new FormData(Test);
formData.set("submit", "1");
Or you could change your test to
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
Please see: https://developer.mozilla.org/en-US/docs/Web/API/FormData/FormData
You must use a Form Element:
An HTML <form> element — when specified, the FormData object will be populated with the form's current keys/values using the name property of each element for the keys and their submitted value for the values. It will also encode file input content.
Consider the following example.
$(function() {
$("#Test").submit(function(e) {
e.preventDefault();
var formData = new FormData(this);
$.ajax({
url: "uploadtest2.php",
type: "POST",
data: formData,
cache: false,
contentType: false,
processType: false,
success: function(result) {
$("#Disp").html(result);
}
});
});
$("#Knopf").click(function() {
$("#Test").submit();
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="Test" action="" method="post" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload" />
</form>
<button id="Knopf" type="submit">Knopf</button>
<div id="Disp">fghfgh</div>
It is better to bind to the submit callback. This way, if the User submits the form or clicks Submit, the callback is triggered. We need to .preventDefault() on the Event to ensure the Form doesn't post or submit the data. Now we can then perform the AJAX call without the page being refreshed.
In your success callback, you must pass in a variable to be used for the returned data. Otherwise result will be undefined.
With the proper FormData, there should be no issue uploading. this in the callback refers to the Form Element itself.
Consider updating your PHP as well:
if(isset($_POST["submit"])) {
Change this to:
if(isset($_POST["fileToUpload"])) {

PHP echo jQuery AJAX request

This is my jQuery request to upload an image file
$('#upload-image').change(function(e){
var file = e.target.files[0];
var imageType = /image.*/;
if (!file.type.match(imageType))
return;
console.log(file);
var form_data = new FormData();
form_data.append('file', file);
console.log(form_data);
$.ajax({
url: 'http://localhost/upload.php',
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'POST',
success: function(response){
console.log(response);
},
error: function(error){
console.log(error);
}
});
});
This is upload.php on local webserver
<?php
header('Access-Control-Allow-Origin: *');
if ( 0 < $_FILES['file']['error'] ) {
echo 'Error: ' . $_FILES['file']['error'] . '<br>';
}
else {
move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $_FILES['file']['name']);
$target_path = $_SERVER['DOCUMENT_ROOT'] . "/uploads/" . $_FILES['file']['name'];
echo $target_path;
}
?>
When I upload the image and send request. It returns and logs for me complete code lines of upload.php, not the result from echo command line that I want. I check console Network tab and see that the response is nothing except complete code of upload.php. It truly does not handle anything server-side. What did I do wrong?
You need to make sure that PHP runs server-side. If there's no PHP handler installed, the server will return the content of your upload.php file as text. I think that's your primary problem.
Based on your platform, you may try:
http://www.wampserver.com/en/ (windows)
https://www.digitalocean.com/community/tutorials/how-to-install-linux-apache-mysql-php-lamp-stack-on-ubuntu-14-04 (Ubuntu)
https://www.mamp.info/en/ (MacOS)
First of all make sure your PHP works, by creating a file called info.php in your webroot folder with the following content
<?php
phpinfo();
This should display your configuration. Then you can start debugging the Javascript. The content type should by multipart/form-data so that the server knows it expects an upload.
Good luck!

Dropzone always return 'empty($_FILES)' as true

I need to add drag and drop to my web page. I'm trying to get dropped image and upload them to my database.
HTML
<form action="parser.php" id="file-up" class="dropzone">
<input type="submit" value="Upload" id="file-up_btn"/>
</form>
JS
Dropzone.autoDiscover = false;
$('#file-up_btn').click(function(e){
var myDropzone = new Dropzone("#myId", {
autoQueue: false,
url: "/parser.php",
});
console.log("Uploading");
});
Dropzone shows that the uploading finished successfully. But it does not show any files in the php file.
<?php
if(!empty($_FILES)){
echo 'Inside';
$temp = $_FILES['file']['tmp_name'];
$dir_seperator = DIRECTORY_SEPARATOR;
$folder = "uploads";
//$destination_path = dirname(__FILE_).$dir_seperator.$folder.$dir_seperator;
$destination_path = tempnam(sys_get_temp_dir(), 'Tux');
echo '<h1>Uploading section $destination_path</h1>';
$target_path = $destination_path.$_FILES['file']['name'];
move_uploaded_file($temp,$target_path);
echo 'Updated';
}else{
echo '<h1>No files</h1>';
}
?>
it always returns No files. I am new to DropZone. Please help me on this. Thanks in advance. :)
Two thinks to check:
id isn't the same.
in js: "#myId"
in html: #file-up or #file-up_btn
There no myid in html to refer so img isn't added to form.
from logical behaviour:
empty($_FILES) is true when no files are transmited
!empty($_FILES) is false because of !. So no file is attach.
Check Developer Tools->Network and check Preserve log. Check what header is sent with what data (maybe nothing is sent etc, it is half success when you can inform if file is added to form data).
Screenshoot to show what we all need to help: developer tools

Can't upload multiple files using ajax

First of all this might be a silly question as there are many topics available on this but seriously I am not being able to get it straight and understand how to make it work.
WHAT I AM TRYING TO DO
I am trying to upload multiple files using AJAX and PHP.
PROBLEM
I cant figure out how to pass the data to the PHP script using AJAX.
I don't want to use a form and a submit button for uploading.
Tried using a form and submitting it using jQuery still couldn't make
it.
HTML
<div id="content">
<div id="heading">Upload your files seamlessly</div>
<a href="#"><div id="upload" class="button" title="Upload your files"><i class="fa fa-cloud-upload fa-align-center" aria-hidden="true"></i>
</div></a>
<a href="view.php"><div id="view" class="button" title="View all files on my cloud"><i class="fa fa-eye fa-align-center" aria-hidden="true"></i>
</div></a>
</div>
<form id="fileupload" method="POST" enctype="multipart/form-data">
<input type="file" multiple name="uploadfile[]" id="uploadfile" />
</form>
JS
<script type="text/javascript">
$(document).ready(function(){
$('#upload').click(function(){
$('input[type=file]').click();
return false;
});
$("#uploadfile").change(function(){
//submit the form here
$('#fileupload').submit();
});
});
</script>
PHP
<?php
if(isset($_FILES['uploadfile'])){
$errors= array();
foreach($_FILES['uploadfile']['tmp_name'] as $key => $tmp_name ){
$file_name = $key.$_FILES['uploadfile']['name'][$key];
$file_size =$_FILES['uploadfile']['size'][$key];
$file_tmp =$_FILES['uploadfile']['tmp_name'][$key];
$file_type=$_FILES['uploadfile']['type'][$key];
if($file_size > 2097152){
$errors[]='File size must be less than 2 MB';
}
//$query="INSERT into upload_data (`USER_ID`,`FILE_NAME`,`FILE_SIZE`,`FILE_TYPE`) VALUES('$user_id','$file_name','$file_size','$file_type'); ";
$desired_dir="storage";
if(empty($errors)==true){
if(is_dir($desired_dir)==false){
mkdir("$desired_dir", 0700); // Create directory if it does not exist
}
if(is_dir("$desired_dir/".$file_name)==false){
move_uploaded_file($file_tmp,"$desired_dir/".$file_name);
}
else{ // rename the file if another one exist
$new_dir="$desired_dir/".$file_name.time();
rename($file_tmp,$new_dir) ;
}
//mysql_query($query);
}
else{
print_r($errors);
}
}
if(empty($error)){
echo "Success";
}
}
?>
Any help would be appreciated.
This is a very simple example of what you want to do.
HTML
Wrap your inputs within a form. Why? Because it is the easiest way to do it.
<form action="process.php" method="post">
<input type="file" multiple name="uploadfile[]">
<input type="submit" value="Upload">
</form>
JavaScript
Attach an onsubmit event handler to your form. Use $.ajax() to send a POST request.
Pass your form element i.e. this into the constructor of a FormData object and use it as your data when you send the request as shown below. You need to make sure that you set processData and contentType as false also for this to work.
$(function () {
$('form').on('submit', function (e) {
e.preventDefault();
// send request
$.ajax({
url: this.action,
type: this.method,
data: new FormData(this), // important
processData: false, // important
contentType: false, // important
success: function (res) {
alert(res);
}
});
});
});
PHP (process.php)
Let's clean up your PHP.
<?php
// always a good idea to turn on errors during development
error_reporting(E_ALL);
ini_set('display_errors', 1);
$dir = './storage';
$errors = [];
if (isset($_FILES['uploadfile'])) {
$files = $_FILES['uploadfile'];
// create directory if it does not exist
!is_dir($dir) && mkdir($dir, 0700);
// validate & upload files
foreach (array_keys($files['tmp_name']) as $key) {
$file = [
'name' => $files['name'][$key],
'size' => $files['size'][$key],
'tmp_name' => $files['tmp_name'][$key],
'type' => $files['type'][$key],
'error' => $files['error'][$key]
];
// skip if no file was given
if ($file['error'] === UPLOAD_ERR_NO_FILE) {
continue;
}
// get file extension
$file['ext'] = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
// generate a unique name (!)
$file['name'] = uniqid() . '.' . $file['ext'];
// validate
if (!file_exists($file['tmp_name']) ||
!is_uploaded_file($file['tmp_name']) ||
$file['error'] !== UPLOAD_ERR_OK) {
$errors[$key] = 'An unexpected error has occurred.';
} elseif ($file['size'] > 2097152) {
$errors[$key] = 'File size must be less than 2 MB';
// upload file
} elseif (!move_uploaded_file($file['tmp_name'], $dir . '/' . $file['name'])) {
$errors[$key] = 'File could not be uploaded.';
}
}
}
if ($errors) {
print_r($errors);
} else {
echo 'no errors';
}
?>
(!) Do keep in mind that uniqid() is actually not unique.

Download File in AJAX Handler

I wrote a small script using only PHP to test file download functionality using a experimental API, where this worked fine. When I decided to commit this code to my project, I added the same code to the handler for my AJAX call, however it does not start the download as it did before.
I believe this is due to the fact I am using AJAX, however as I was using header() to initiate the file download on the client, I am at a loss as to how to work around this.
Can anyone suggest an alternative method to do this now?
AJAX:
$.ajax({
type: "POST",
url: "handler.php",
data: { 'action': 'downloadFile', 'filename': curSelectedFile },
dataType: 'json',
success: function(data)
{
//Success
}
});
PHP Handler:
case "downloadFile":
{
$filename = '';
if (isset($_POST["filename"]))
{
$filename = $_POST["filename"];
}
$pos = 0; // Position in file to start reading from
$len = 32; // Length of bytes to read each iteration
$count = 0; // Counter for the number of bytes in the file
do
{
$result = $fm->getFileChunk($filename, $pos, $len);
$chunk = $result->result;
if (!empty($chunk))
{
$chunk = base64_decode($chunk);
$count += strlen($chunk);
echo $chunk;
}
$pos += $len;
}
while (!empty($chunk));
header('Content-Disposition: attachment; filename="'. $filename .'"');
header('Content-Type: application/octet-stream');
header('Content-Length: ' . $count);
$response['status'] = "success";
echo json_encode($response);
break;
}
You can encode your file in base64 and create File Object using JavaScript.
I wouldn't recommend this for large files!
Alternative:
Save your file on server and you can just retrieve file location and redirect using location.href in Ajax callback.
You can decode base64 using atob() and create typed array. refer to following link for creating Binary Object on client side. You create typed array like answered here.

Categories

Resources