I need to pass files and other data to ajax.
My code:
var doc = new jsPDF('p', 'pt', 'a4'); // basic create pdf
var pdf = doc.output('blob');
var data = "";
if (flagSend == 1) {
data = new FormData($("#sendInvoiceForm")[0]);
data.append('flagSend', 1);
var send_invoice_subject = $("#send_invoice_subject").val();
} else {
data = new FormData();
data.append('flagSend', 0);
}
data.append('data', pdf);
data.append('invoice_number', invoice_number);
$.ajax({
type: 'POST',
data: data,
processData: false,
contentType: false,
url: sJSUrlSavePdfInvoiceToServer,
dataType: 'json',
success: function (data) {
}
});
In my 'data' I pass a pdf file, and get it in php with $_FILES['data'].
It works well in Chrome,Firefox. But in Safari there is no $_FILES['data'], there is $_REQUEST['data'] - [object Blob]
So I can't upload files in Safari:
if (move_uploaded_file($_FILES["data"]["tmp_name"], $target_file)) {
}
because there is no $_FILES['data'] field.
How can I solve this problem?
Thanks.
Anybody know reason?
Related
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);
}
});
});
I need to download an XML received from a controller, but I need the prompt to write a the name and the location where the file will be saved.
First question: is optimal to send the xml like I did in this code or I should send it like a file in some way.
Second question: receiving the xml or the xml file, how can open the prompt and finally save the xml like a file?
[HttpPost]
public ActionResult ExportFiles(string clientName, string currenthcsystem)
{
try
{
var systemActionsConfigurationData = service.GetHcSystemActionsConfigurationData(clientName,currenthcsystem);
XmlSerializer xsSubmit = new XmlSerializer(typeof(HcSystemActionsConfigurationData));
var xml = "";
using (var sww = new StringWriter())
{
using (XmlWriter writer = XmlWriter.Create(sww))
{
xsSubmit.Serialize(writer, systemActionsConfigurationData);
xml = sww.ToString();
}
}
return Content(xml, "text/xml");
}
catch (Exception)
{
throw;
}
}
$('#exportButton').on("click", function () {
var clientName = $(actionsButtons).data('clientname');
var currentHCSystem = $(actionsButtons).data('hcsystemname');
// Create FormData object
var parameters = new FormData();
parameters.append("clientName", clientName);
parameters.append("currentHCSystem", currentHCSystem);
$.ajax({
url: $(actionsButtons).data('export'),
type: 'POST',
data: parameters,
cache: false,
processData: false,
contentType: false,
success: function (response) {
//logic to open the prompt and finally download the xml
},
error: function (err) {
}
});
});
We are Generating blob value and want to get it inserted into the database through SQL Server.
We are able to pass the blob value and through the help of Ajax call we are trying to get it to insert but we are receiving the error Uncaught (in promise) TypeError: Failed to execute 'array buffer on 'Blob': Illegal invocation code. And in WebServices, we are passing it as byte value byte[] BLOB while in SQL we are using var binary(max) to store the value.
async function pdfhandler() {
let pdfBlob = '1';
var mystring = "Hello World!";
pdfBlob = new Blob([mystring]);
updateblobdata(pdfBlob);
console.log(pdfBlob);
}
function updateblobdata(blobvalue) {
debugger;
/// Insert Blob into Database ///
console.log('updateblobdata called');
const urlParams = new URLSearchParams(window.location.search);
const myParamtag = urlParams.get('104');
const mymodelval = urlParams.get('DuganHosp-0002');
var wonumval = '104'; var tagnumval = 'DuganHosp-0002';
var Modeval = 'U';
var BLOBval = blobvalue;
$.ajax({
url: 'TestTool_WebService.asmx/UpdateHtmlBLOBContent',
data: {
WoNum: wonumval,
Tagnum: tagnumval,
BLOB: BLOBval,
Mode: Modeval,
},
method: 'post',
dataType: 'json',
contentType: false,
processData: false,
cache: false,
success: function (data) { },
});
}
You can send files only with content-type: multipart/form-data.
function updateblobdata(blobvalue) {
const formData = new FormData();
formData.append('blob', blobvalue);
$.ajax({
url: 'TestTool_WebService.asmx/UpdateHtmlBLOBContent',
data: formData,
method: 'post',
dataType: 'json',
contentType: 'multipart/form-data',
processData: false,
cache: false,
success: function (data) { },
});
}
No Still its not working.Its not coming to this point for blob value.
[WebMethod]
public void UpdateHtmlBLOBContent(string WoNum, string Tagnum, byte[] BLOB, string Mode)
{
string htmldoc = null;
using (SqlConnection con = new SqlConnection(ConfigurationSettings.AppSettings["ConStr1"]))
{
SqlCommand cmd = new SqlCommand("TestTool_PrototypeprocBlobRun", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#Workorder", WoNum);
cmd.Parameters.AddWithValue("#Equipment", Tagnum);
cmd.Parameters.AddWithValue("#HTML_blob", BLOB);
cmd.Parameters.AddWithValue("#MODE", "U");
con.Open();
int i = cmd.ExecuteNonQuery();
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
htmldoc = "Success";
}
dr.Close();
}
Context.Response.Write(htmldoc);
}
}
I'm trying to send an ajax form to a controller, but the data attribute arrive empty to the controller, this is my code:
var fd = new FormData();
fd.append('asd', 123);
console.log(fd);
var idServicio = $("#id-building-form-add-new-stand").val();
var idEdificio = $("#id-service-form-add-new-stand").val();
var piso = $("#id-floor-form-add-new-stand").val();
var idJornada = $("#id-jornada-form-add-new-stand").val();
fd.append("idServicio", idServicio);
fd.append("idEdificio", idEdificio);
fd.append("piso", piso);
fd.append("idJornada", idJornada);
fd.append("jsonStand", JSON.stringify(jsonStand));
fd.append("accion", "1");
console.log(fd);
after I put my ajax code:
$.ajax({
method: "POST",
mimeType: "multipart/form-data",
url: epStand,
processData: false,
contentType: false,
data: fd,
success: function (statusM) {
//toggleModalCargando();
var data = JSON.parse(statusM);
if (data.status === 1) {
console.log("éxito");
$.unblockUI();
} else {
if (data.status === 0) {
$.unblockUI();
throwAlert(data.dataObject[0].message, "error");
} else {
$.unblockUI();
throwAlert(data.descripcion, "error");
}
}
}
});
However the fd variable is empty in all my logs console and of course in the controller.
I am trying to upload a image to Database using Javascript on client and PHP on server.
first image is selected from the gallery.
after zooming and cropping the image is passed to database
The Problem is when iam trying to submit the cropped image value is not passed to the php the actual uploaded input "File" Value is Being Passed, but i need the cropped areas value to be passed to PHP.
For testing purpose if all the js are required i can provide it.
Js: This Crops the image
$(function() {
$('.image-editor').cropit({
exportZoom: 1.25,
imageBackground: true,
imageBackgroundBorderWidth: 40,
});
$('.export').click(function() {
var imageData = $('.image-editor').cropit('export');
window.open(imageData);
});
});
HTML:
<form id="uploadForm" class="image-editor">
<input type="file" class="cropit-image-input">
<!-- .cropit-image-preview-container is needed for background image to work -->
<div class="cropit-image-preview-container">
<div class="cropit-image-preview"></div>
</div>
<div class="image-size-label">
Resize image
</div>
<input type="range" class="cropit-image-zoom-input">
<input type="submit" class="export">Export</input >
</form>
Ajax: ajax sends the data to php
$(document).ready(function (e) {
$("#uploadForm").on('submit', (function (e) {
e.preventDefault();
$.ajax({
url: "upload.php",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData: false,
success: function (data) {
$("#targetLayer1").html(data);
},
error: function () {}
});
});
});
PHP:
if(count($_FILES) > 0) {
if(is_uploaded_file($_FILES['userImage']['tmp_name'])) {
$mysl = mysqli_connect("localhost", "root", "root","test");
$imgData =addslashes(file_get_contents($_FILES['userImage']['tmp_name']));
$imageProperties = getimageSize($_FILES['userImage']['tmp_name']);
$sql = "UPDATE output_images SET imageType ='{$imageProperties['mime']}',imageData= '{$imgData}' WHERE imageId='16'";
$current_id = mysqli_query($mysl,
$sql) or die("<b>Error:</b> Problem on Image Insert<br/>" . mysqli_error());;
if(isset($current_id)) {
echo "done";
}
}
}
First, take a look at this: Can I pass image form data to a PHP function for upload?
I think the issue is here: var imageData = $('.image-editor').cropit('export');. Since this new image is never a part of the form, there is no way to pass it via AJAX.
In your JS/JQuery, I would advise:
var imageData = '';
$(function() {
$('.image-editor').cropit({
exportZoom: 1.25,
imageBackground: true,
imageBackgroundBorderWidth: 40,
});
$('.export').click(function() {
imageData = $('.image-editor').cropit('export');
window.open(imageData);
});
});
$(document).ready(function (e) {
$("#uploadForm").on('submit', (function (e) {
e.preventDefault();
var fd = new FormData(this);
fd.append( imageData, file );
$.ajax({
url: "upload.php",
type: "POST",
data: fd,
contentType: false,
cache: false,
processData: false,
success: function (data) {
$("#targetLayer1").html(data);
},
error: function () {}
});
});
});
EDIT
In your example, you never defined a name or id attribute for your input, so there would be no way for PHP to index the $_FILES global. Could try $_FILES[0]. I would advise assigning that in your form or when you post it.
You can adjust the myFormData.append(name, file, filename);. So it would be:
fd.append('crop-image', imageData, 'crop-image.jpg');
Then in PHP, you call it using $_FILES['crop-image']. If you want to pass the file name from the form:
$(document).ready(function (e) {
$("#uploadForm").on('submit', (function (e) {
e.preventDefault();
var fd = new FormData(this);
var origFileName = $("input[type='file']").val();
var startIndex = (origFileName.indexOf('\\') >= 0 ? origFileName.lastIndexOf('\\') : origFileName.lastIndexOf('/'));
var filename = origFileName.substring(startIndex);
if (filename.indexOf('\\') === 0 || filename.indexOf('/') === 0){
filename = filename.substring(1);
}
var cropFileName = "crop-" + filename;
fd.append('crop-image' imageData, cropFileName );
$.ajax({
url: "upload.php",
type: "POST",
data: fd,
contentType: false,
cache: false,
processData: false,
success: function (data) {
$("#targetLayer1").html(data);
},
error: function () {}
});
});