I am able to send data on .cs page and image also save in folder but it's corrupted and image size is 0.. i am totally confused that where is the error
Please see the JQUERY CODE & C# CODE also
JQUERY code
<script type="text/javascript">
$(document).ready(function () {
$("#submitPhoto").click(function () {
var photo = $("#uploadPhoto").get(0);
var file = photo.files;
var Photo_Path = $("#uploadPhoto").val();
var extenssion = Photo_Path.split('.').pop().toUpperCase();
if (Photo_Path == "") {
alert('Please Choose Photo');
return;
}
if (extenssion != 'JPEG' && extenssion != 'JPG' && extenssion != 'jpg') {
alert('Invalid File[JPEG,JPG is acceptable]');
return;
}
if (file.size < 4000 || file.size > 14000) {
alert('Photo Size Must be Below 12Kb and Above 4Kb ');
return;
}
var id = $("#submitPhoto").attr('id');
$.ajax({
type: "POST",
contentType: "multipart/form-data",
url: "finalstep-registration.aspx?photoPath=" + Photo_Path + "&id=" + id + "&check=imgUpload",
data: file,
datatype: 'json',
async: false,
processData: false,
success: function (data) {
alert('Image successfully Uploaded');
},
error: function ()
{ console.log('there is some error'); }
});
});
</script>
C# code
By which image are save in folder and name are save in database
I am calling uploadPhoto()function on pageload using query string
public void uploadPhoto(string photoPath,string id)
{
//HttpContext context = HttpContext.Current;
//int regNo = Convert.ToInt32(Session["restrationNumber"].ToString());
int regNo = 1001;
if (id == "submitPhoto")
{
FileInfo CustPic = new FileInfo(photoPath);
System.IO.Stream fileContent = Request.InputStream;
FileStream fileStream = File.Create(Server.MapPath("~/photo/") + CustPic.Name);
fileContent.Seek(0, System.IO.SeekOrigin.Begin);
fileContent.CopyTo(fileStream);
//System.Web.Hosting.HostingEnvironment.MapPath("~/photo/");
string query = "update userDetails set photo='"+photoPath+ "' where regNo="+regNo+"";
int a = bl.executenonquery(query);
if (a == 1)
Response.Write("Photo is uploaded successfully");
else
Response.Write("Oops, We can't upload your photo. try again");
//Session["photo"] = CustPic.Name;
}
}
Check and tell me where i am doing wrong
Related
I have been working on a website incorporating the autodesk-forge viewer (more details can be seen on my past questions). I have successfully made many autodesk-forge viewer functions in a standard javascript (.js) file. These functions include displaying the viewer, and isolating to a particular part, when an external button is pressed.
Currently I have a main html/php home page where I have included my javascript file with all my forge functions using <script src="MyForgeFunctions.js"></script>
These functions are accessed through a button, which successfully displays the viewer in the html page. Attached to my main php/html page, another html/php page was added through an iframe html reference (<iframe src="URL.php"></iframe>). My home page displays the main machines we make, while the embedded php/html page displays all the stations within the machine. I have also included the MyForgeFunctions.js inside this second php/html page. Because of the way the website is set up, I need to be able to access the viewer in both web pages. However, when I attempt to access the viewer from the second html page, I get a message that the viewer is undefined. Below is my code from MyForgeFunctions.js.
var ext = '';
var dim = '';
var assemblyname = '';
function getAssemblyName(){
assemblyname = sessionStorage.getItem("assemblyName");
//var ext = partname.substr(partname.lastIndexOf('.'));
ext = assemblyname.split('.');
dim = ext[0] + ':1';
console.log(assemblyname);
console.log(dim);
if (dim !== ''){
isolateSelected();
}
}
//function to get part name from __MachineParts.php
var partname = '';
var extension = '';
var namewithoutextension = '';
function getPartName(){
partname = sessionStorage.getItem("partName");
//var ext = partname.substr(partname.lastIndexOf('.'));
extension = partname.split('.');
namewithoutextension = extension[0] + ':1'
console.log(partname);
console.log(namewithoutextension);
if (namewithoutextension !== ''){
isolateSelectedPart();
}
}
/*******************************************************************************
*
* AUTODESK FORGE VIEWER CODE (HTTP REQUESTS)
*
*******************************************************************************/
//VARIABLE DECLARATION
var code = '';
var access_token = '';
const hub = 'xxxxxxxxxxxxxxxxxxxxxxxxxxx';
const project ='xxxxxxxxxxxxxxxxxxxxxxxxxxx';
const folder='xxxxxxxxxxxxxxxxxxxxxxxxx';
const item = 'xxxxxxxxxxxxxxxxxxxxxxxxx';
var itemid = '';
var urn = '';
var urn2 = '';
//allow the program to view data from autodesk
function authorize(){
window.location.href = "https://developer.api.autodesk.com/authentication/v1/authorize?response_type=code&client_id=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx&redirect_uri=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx&scope=data:read data:write bucket:read viewables:read bucket:create data:create";
}
//grab the code from the url
function getCode(){
const querystring = window.location.search;
// console.log(querystring);
const urlParams = new URLSearchParams(querystring);
code = urlParams.get('code');
// console.log(code);
}
//call the function to get the code right away, and obtain a token
getCode();
getToken();
//function to obtain access token
function getToken(){
$.ajax({
method: 'POST',
url: 'https://developer.api.autodesk.com/authentication/v1/gettoken',
headers: {
'Content-Type':'application/x-www-form-urlencoded'
},
data:'client_id=dm2VLfnwJ6rYHKPAg7dG6l9yVbBQPGlH&client_secret=HRMpOPusLhsVoIMk&grant_type=authorization_code&code=' + code + '&redirect_uri=http://team/__MachineViewerMV.php',
success:function(response){
// console.log(response);
access_token = response.access_token;
console.log(access_token);
}
})
}
//Grab desired file id from project folder
function getItem(){
$.ajax({
method:'GET',
url: 'https://developer.api.autodesk.com/data/v1/projects/' + project + '/folders/' + item + '/contents',
headers:{
Authorization:'Bearer ' + access_token
},
/* beforeSend:function(before){
if(access_token !== '' && viewer !==''){
destroyViewer();}
},*/
success:function(response){
//console.log(response);
// folder = response.data[0].id;
// console.log(folder);
// itemid = response.data[0].id;
//console.log(itemid);
console.log(response);
for (var i = 0; i<response.data.length; i++){
//console.log(response.data[i].attributes.displayName);
if(response.data[i].attributes.displayName == fileName){
//console.log('hooray');
itemid = response.data[i].id;
console.log(itemid);
getVersion();
break;
}
else if (response.data[i].attributes.displayName !== fileName){
itemid = '';
}
}
},
error:function(error){
authorize();
}
})
}
function get2dItem(){
$.ajax({
method:'GET',
url: 'https://developer.api.autodesk.com/data/v1/projects/' + project + '/folders/' + item + '/contents',
headers:{
Authorization:'Bearer ' + access_token
},
/*beforeSend:function(before){
if(access_token !== '' && viewer !== ''){
destroyViewer();}
},*/
success:function(response){
//console.log(response);
// folder = response.data[0].id;
// console.log(folder);
// itemid = response.data[0].id;
//console.log(itemid);
console.log(response);
for (var i = 0; i<response.data.length; i++){
//console.log(response.data[i].attributes.displayName);
if(response.data[i].attributes.displayName == fileName2d){
//console.log('hooray');
itemid = response.data[i].id;
console.log(itemid);
getVersion();
break;
}
else if (response.data[i].attributes.displayName !== fileName2d){
itemid = '';
}
}
},
error:function(error){
authorize();
}
})
}
//get version of the file using its id
function getVersion(){
$.ajax({
method:'GET',
url: 'https://developer.api.autodesk.com/data/v1/projects/' + project + '/items/' + itemid + '/versions',
headers:{
Authorization:'Bearer ' + access_token
},
success:function(response){
//console.log(response);
urn = btoa(response.data[0].relationships.storage.data.id);
console.log(urn);
translateToSVF();
}
})
}
function translateToSVF(){
$.ajax({
method: 'POST',
url:"https://developer.api.autodesk.com/modelderivative/v2/designdata/job",
headers:{
"content-type": "application/json",
Authorization: "Bearer " + access_token
},
data:JSON.stringify({
"input":{ "urn":urn
},
"output": {
"formats": [
{
"type": "svf",
"views": [
"2d",
"3d"
]
}
]
}
}),
success:function(response){
// console.log(response);
urn2 = response.urn;
console.log(urn2);
checkStatus();
}
})
}
function checkStatus(){
$.ajax({
method: 'GET',
url: "https://developer.api.autodesk.com/modelderivative/v2/designdata/" + urn2 + "/manifest",
headers:{
Authorization: "Bearer " + access_token
},
success: function(response){
console.log(response);
if (response.progress == 'complete'){
displayViewer();
}
else if (response.progress !== 'complete'){
alert('File Still Uploading, Press the Display Button Again!');
}
}
})
}
//function to get list of viewables\
var guid = '';
function getViewable(){
$.ajax({
method:'GET',
headers:{
Authorization: "Bearer " + access_token
},
url: 'https://developer.api.autodesk.com/modelderivative/v2/designdata/' + urn2 + '/metadata',
success:function(response){
console.log(response);
guid = response.data.metadata[0].guid;
console.log(guid);
}
})
}
//funciton to get the list of items within a model
function getTree(){
$.ajax({
method: 'GET',
headers:{
Authorization: "Bearer " + access_token
},
url:'https://developer.api.autodesk.com/modelderivative/v2/designdata/' + urn2 + '/metadata/' + guid + '/properties',
success:function(response){
console.log(response);
}
})
}
/**********************************************************************************
*
* FUNCTION TO DISPLAY THE VIEWER IN THE HTML PAGE
*
**********************************************************************************/
var viewer;
function displayViewer(){
//var viewer;
var options = {
env: 'AutodeskProduction',
api: 'derivativeV2', // for models uploaded to EMEA change this option to 'derivativeV2_EU'
getAccessToken: function(onTokenReady) {
var token = access_token;
console.log(token);
var timeInSeconds = 3600; // Use value provided by Forge Authentication (OAuth) API
onTokenReady(token, timeInSeconds);
}
};
Autodesk.Viewing.Initializer(options, function() {
var htmlDiv = document.getElementById('forgeViewer');
viewer = new Autodesk.Viewing.Private.GuiViewer3D(htmlDiv);
var startedCode = viewer.start();
// sessionStorage.setItem("viewer", viewer);
if (startedCode > 0) {
console.error('Failed to create a Viewer: WebGL not supported.');
return;
}
console.log('Initialization complete, loading a model next...');
});
var documentId = 'urn:'+urn2;
Autodesk.Viewing.Document.load(documentId, onDocumentLoadSuccess, onDocumentLoadFailure);
function onDocumentLoadSuccess(viewerDocument) {
var defaultModel = viewerDocument.getRoot().getDefaultGeometry();
viewer.loadDocumentNode(viewerDocument, defaultModel);
console.log(viewer);
}
function onDocumentLoadFailure() {
console.error('Failed fetching Forge manifest');
}
}
//function to hide the viewer
function destroyViewer(){
console.log(viewer);
viewer.finish();
viewer = null;
Autodesk.Viewing.shutdown();
}
/*****************************************************************************
* FUNCTIONS TO MODIFY THE VIEWER TO ZOOM INTO THE CORRECT PART/ASSEMBLY
*/
function isolateSelected(){
console.log(dim);
console.log(viewer);
viewer.search(dim, function(dbIds) {
// viewer.search('"' + 'M-109408 FOLDING PLOUGH:2' + '"', function(dbIds) {
console.log(dbIds.length);
getSubset(dbIds, 'label', dim, function(dbIds) {
// getSubset(dbIds, 'label', 'M-109408 FOLDING PLOUGH:2', function(dbIds) {
// getSubset(dbIds, property.name, 'M-54439 POST TUBING:1', function(dbIds) {
//getSubset(dbIds, property.name, property.value, function(dbIds){
var it = viewer.model.getData().instanceTree;
//console.log(it);
for (i = 0; i<dbIds.length; i++){
var namepart = it.getNodeName(dbIds[i]);
if (namepart !== undefined){
console.log(dbIds);
console.log(namepart);}}
/* for (i = 121; i<381;i++){
var dbId = i;
var it = NOP_VIEWER.model.getData().instanceTree;
var name = it.getNodeName(dbId);
console.log(name);}*/
viewer.isolate(dbIds)
viewer.select(dbIds);
viewer.utilities.fitToView();
})
}, function(error) {})
}
function isolateSelectedPart(){
console.log(namewithoutextension);
viewer.search(namewithoutextension, function(dbIds) {
// viewer.search('"' + 'M-109408 FOLDING PLOUGH:2' + '"', function(dbIds) {
console.log(dbIds.length);
getSubset(dbIds, 'label', namewithoutextension, function(dbIds) {
// getSubset(dbIds, 'label', 'M-109408 FOLDING PLOUGH:2', function(dbIds) {
// getSubset(dbIds, property.name, 'M-54439 POST TUBING:1', function(dbIds) {
//getSubset(dbIds, property.name, property.value, function(dbIds){
var it = viewer.model.getData().instanceTree;
//console.log(it);
for (i = 0; i<dbIds.length; i++){
var namepart = it.getNodeName(dbIds[i]);
if (namepart !== undefined){
console.log(dbIds);
console.log(namepart);}}
/* for (i = 121; i<381;i++){
var dbId = i;
var it = NOP_VIEWER.model.getData().instanceTree;
var name = it.getNodeName(dbId);
console.log(name);}*/
viewer.isolate(dbIds)
viewer.select(dbIds);
viewer.utilities.fitToView();
})
}, function(error) {})
}
//function to find the dbid of the part/assembly
function getSubset(dbIds, name, value, callback) {
console.log("getSubset, dbIds.length before = " + dbIds.length)
viewer.model.getBulkProperties(dbIds, {
propFilter: [name],
ignoreHidden: true
}, function(data) {
var newDbIds = []
for (var key in data) {
var item = data[key]
// console.log(item.properties);
if (item.properties[0].displayValue === value) {
newDbIds.push(item.dbId)
}
}
console.log("getSubset, dbIds.length after = " + newDbIds.length)
callback(newDbIds)
}, function(error) {})
}
Because of how the webpage is set up, when I needed to use a variable from the second web page in the first, I used sessionStorage.getItem and sessionStorage.setItem. I have also made a simple function as so inside MyForgeFunctions.js:
function checkViewer(){
console.log(viewer);
}
I then included a button in both html pages to execute the function with an onclick event. When the function is run from the first/home html page the following is displayed:
T {globalManager: e, clientContainer: div#forgeViewer, container: div.adsk-viewing-viewer.notouch.dark-theme.quality-text, config: {…}, contextMenu: o, …}. Which is normal for the viewer, but when the function is executed from the second html page, the viewer is undefined. Any help as to why this is happening or any solutions will be greatly appreciated. Cheers!
From the iframe, in order to access the viewer inside the main web page, I had to use (parent.viewer).
I am uploading files onto a folder within my application using the code below. I would like to know how I can specify which type of files can be uploaded into that folder in my case I only want the user to be able to upload xls,xlxs and csv files. The user should not be allowed to upload docx or images etc
function OnUpload(evt) {
var files = $("#fileUpload").get(0).files;
if (files.length > 0) {
ShowUploadProgress();
if (window.FormData !== undefined) {
var data = new FormData();
for (i = 0; i < files.length; i++) {
data.append("file" + i, files[i]);
}
$.ajax({
type: "POST",
//url: "/api/ExcelBulkUpload",
url: "/api/FileUpload",
contentType: false,
processData: false,
data: data,
success: function (results) {
ShowUploadControls();
$("#uploadResults").empty();
for (i = 0; i < results.length; i++) {
$("#uploadResults").append($("<li/>").text(results[i]));
}
///"location.href='<%: Url.Action("Upload", "Controller") %>'"
window.location.href = '#Url.Action("UploadPage", "Home")';
},
error: function (xhr, ajaxOptions, thrownError) {
ShowUploadControls();
alert(xhr.responseText);
}
});
} else {
alert("Your browser doesn't support HTML5 multiple file uploads! Please use another browser.");
}
}
}
What I have researched so far
_validFileExtensions = [".xls", ".xlsx"];
var sFileName = oInput.value;
if (sFileName.length > 0) {
var blnValid = false;
for (var j = 0; j < _validFileExtensions.length; j++) {
var sCurExtension = _validFileExtensions[j];
if (sFileName.substr(sFileName.length - sCurExtension.length, sCurExtension.length).toLowerCase() == sCurExtension.toLowerCase()) {
blnValid = true;
//$('#fileinput').val('');
break;
}
You can check file extension, and based on that if file extension are allowed then call upload function, else display message that selected file not allowed to upload.
Se below example.
Note : Only client side validation is not enough, also put validation on server side.
$(document).on("change","#myfile", function (e) {
var _theFormFile = $('#myfile')[0].files[0];
var ext = getExt(_theFormFile.name);
if(ext == ".xls" || ext == ".xlxs " || ext == ".csv") {
alert('call upload file function');
} else {
alert('display false message')
return false;
}
});
function getExt(filename) {
var ext = filename.split(".");
var cnt = ext.length;
ext = ext[cnt - 1];
ext = "." + ext.toLowerCase();
return ext;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type='file' name="myfile" id="myfile">
First you can select what file types the users can input by default with
<input accept=".fileType" />
And then check the filetyp if they changed the filter
function upload(){
var fileName = document.getElementById("file").files[0].name;
console.log(fileName.substr(fileName.lastIndexOf(".")));
}
<input id="file" type="file" accept=".xls,.xlxs,.csv" />
<button onClick="upload()">send</button>
In my application, I have so far managed to upload images to the server. Now I would like to set an uploaded image as a background dynamically using javascript in ASP.NET MVC5. Here is my code. This part reads file from local storage
jQuery(document).ready(function ()
{
jQuery("#imageBrowes").change(function ()
{
var File = this.files;
if (File && File[0])
{
ReadImage(File[0]);
}
})
})
var ReadImage = function(file)
{
var reader = new FileReader;
var image = new Image;
reader.readAsDataURL(file);
reader.onload = function(_file)
{
image.src = _file.target.result;
image.onload = function()
{
var height = this.height;
var width = this.width;
var type = file.type;
var size = ~~(file.size / 1024) + "KB";
jQuery("#targetImg").attr('src', _file.target.result);
jQuery("#description").text("Size:" + size + ", " + height + "X " + width + ", " + type + "");
jQuery("#imgPreview").show();
}
}
}
This part stores the image into the file server system:
var ClearPreview = function(){
jQuery("#imageBrowes").val('');
jQuery("#description").text('');
jQuery("#imgPreview").hide();
}
var Uploadimage = function()
{
var file = jQuery("#imageBrowes").get(0).files;
var data = new FormData;
data.append("ImageFile", file[0]);
jQuery.ajax({
type: "Post",
url: "/Home/ImageUpload",
data: data,
contentType: false,
processData: false,
success: function (response) {
ClearPreview();
jQuery("#uploadedImage").append('<img src="/elements-images/' + response + '" class="img-responsive thumbnail"/>');
}
})
}
This the action that is called up in the above javascript:
public ActionResult ImageUpload(ProductViewModel model)
{
var file = model.ImageFile;
if (file != null)
{
var fileName = Path.GetFileName(file.FileName);
var extention = Path.GetExtension(file.FileName);
var filenamewithoutextension = Path.GetFileNameWithoutExtension(file.FileName);
file.SaveAs(Server.MapPath("/elements-images/" + file.FileName));
}
return Json(file.FileName, JsonRequestBehavior.AllowGet);
}
So basically the image file is saved into elements-images folder. How do I then set a specific image from that folder into a background image?
Javascript side preview
For javascript side preview of the file, Please change your this line
jQuery("#targetImg").attr('src', _file.target.result);
to
jQuery("#targetImg").attr('src', "data:" + file.type + ";base64," + btoa(_file.target.result) );
Preview after upload on server
To show image after server response your code seems to be correct. It seems you need to change this line in action result
return Json(file.FileName, JsonRequestBehavior.AllowGet);
so it looks like this
public ActionResult ImageUpload(ProductViewModel model)
{
var file = model.ImageFile;
string fileName = string.Empty;
if (file != null)
{
fileName = Path.GetFileName(file.FileName);
var extention = Path.GetExtension(file.FileName);
var filenamewithoutextension = Path.GetFileNameWithoutExtension(file.FileName);
file.SaveAs(Server.MapPath("/elements-images/" + file.FileName));
}
return Json(fileName, JsonRequestBehavior.AllowGet);
}
I'm trying to upload a file and send that via api as a file.But not getting working. Here is my used for upload and send my file to api.
But it most probably terns to the error message.
$(document).on('change', '#txtUploadFile', function(e){
var files = e.target.files;
if (files.length > 0) {
if (this.value.lastIndexOf('.xlsx') === -1){
alert('Only ods files are allowed!');
this.value = '';
return;
}
if (window.FormData !== undefined) {
var data = new FormData();
for (var x = 0; x < files.length; x++){
data.append("file" + x, files[x]);
}
$.ajax({
type: "POST",
contentType: "multipart/form-data",
url: 'http://localhost/clicportaltest/rest/clicadmin/uploadExcel',
data:{file:file},
success: function(result) {
console.log(result);
},
error: function (xhr, status, p3, p4){
var err = "Error " + " " + status + " " + p3 + " " + p4;
if (xhr.responseText && xhr.responseText[0] == "{")
err = JSON.parse(xhr.responseText).Message;
console.log(err);
}
});
} else {
alert("This browser doesn't support HTML5 file uploads!");
}
}
});
$(function(){
$('#submitUpload').on('click', function(){
var file = document.getElementById("upload").files[0];
var form = new FormData();
form.append("file", file);
var settings = {
"async": true,
"crossDomain": true,
"url": "http://localhost/clicportaltest/rest/clicadmin/uploadExcel",
"method": "POST",
"processData": false,
"contentType": false,
"mimeType": "multipart/form-data",
"data": form
};
$.ajax(settings).done(function (response) {
console.log(response);
});
});
});
You can't JSON.stringify data because FormData doesn't have a toJSON() method, so it is treated as a plain object which results in "{}".
You can either implement your own FormData.prototype.toJSON method or just convert data to a string or a plain object in your handler. How the stringified representation of data should be formatted depends entirely on how your API expects it to be.
So the problem is: a user uplaods a file. I use е.PreventDefault(); to prevent the page from refreshing after the upload. Under the file upload form i've made a list of all the user's file names. Obviously the newly uploaded file name isn't in the list. After refreshing the page it gets in the list, but the business logic is that the file's name should go in the list withouth refreshing the page.
function showNewFileProperies() {
var xhttp;
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("results").innerHTML = xhttp.responseText;
}
};
xhttp.open("GET", "../../app/Models/UserFiles.php" , true);
xhttp.send();
}
This is the request with which I thought my problem would be solved.
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class UserFiles extends Model{
protected $table = 'files';
public function getUserFiles(){
$getFiles = Filecontent::where('userid', Auth::id())->get();
foreach($getFiles as $getFile) {
$result = $getFile->filename;
return $result;
}
}
}
I'm using Laravel and Dropzone.js. The js code i put in the success event of dropzone.js
Sorry for the delay in response. Here is what I used to achieve what you are describing. Sorry for the bad indenting but this editor is really bad.
Dropzone.options.documentDropzone = {
paramName: "file",
dictDefaultMessage: "Drag your document over this box to upload or click here",
maxFilesize: 100, // MB
maxFiles: 10,
addRemoveLinks: true,
dictRemoveFile: 'Remove Attachment',
accept: function(file, done) {
done();
},
init: function() {
this.on("addedfile", function(file) {
busy_uploading = true;
});
this.on('removedfile', function(file){
remove_file(file.previewElement, file.fileID);
if(this.getUploadingFiles().length === 0 && this.getQueuedFiles().length === 0) {
busy_uploading = false;
}
});
this.on("complete", function (file) {
if(this.getUploadingFiles().length === 0 && this.getQueuedFiles().length === 0) {
busy_uploading = false;
}
});
},
success: function(file, response) {
response = JSON && JSON.parse(response) || $.parseJSON(response);
if(response.error) {
var node, _i, _len, _ref, _results;
var message = response.error;
file.previewElement.classList.add("dz-error");
_ref = file.previewElement.querySelectorAll("[data-dz-errormessage]");
_results = [];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
node = _ref[_i];
_results.push(node.textContent = message);
}
return _results;
} else {
for(var i = 0; i < response.file_id.length; i++) {
file.fileID = response.file_id[i];
file.fileEXT = response.file_ext[i];
add_file_id(response.file_id[i]);
//You can add the uploaded item in your list here
}
return file.previewElement.classList.add("dz-success");
}
}
};
So this is roughly what I used. You can simply add the item on your list in the success function since that is where you will get the response from the server.
I did not include the php because it is just your basic upload script. This will work with as many files as you wish.
If you need more help just add a comment and I will try to assist you as best I can.
Actually I came up with this:
public function getCurrentFile(){
$userid = Auth::id();
$getFiles = File::where('userid', $userid)->orderBy('created_at', 'desc')->take(1)->get();
foreach($getFiles as $getFile) {
$result = $getFile;
$json = json_encode($result); //make it as json
return $json;
//echo $result;
}
}
Then I routed this model and in the js I've added:
success: function(file) {
$(function ()
{
$.ajax({
async: true,
url: "../public/currentfile",
dataType: 'json',
method:'get',
complete: function(data)
{
console.log(data.responseJSON);
var created_at = data.responseJSON['created_at'];
var filesize = data.responseJSON['filesize'];
var filename = data.responseJSON['filename'];
var fileid = data.responseJSON['fileid'];
$( "#results .tableheaders" ).after("<tr><td>" + fileid + "</td><td>" + filename + "</td><td>" + filesize + "</td><td>" + created_at + "</td></tr>");
}
});
});
if (file.previewElement) {
return file.previewElement.classList.add("dz-success");
}
}
And it seems to work...for now :D I'm not a JS guy and I don't even know how I managed to do this :D