Image Upload doesn't work in Server. Works fine in localhost - ajax

So, this code works just fine in localhost. It deletes the previous image and uploads the new one. It does nothing on server however. Any clue?
I have used AJAX for asynchorous call By the way if that makes a difference.
var db=Database.Open("StarterSite");
var contentQuery="Select * from Contents where id =#0";
var content=db.QuerySingle(contentQuery,"1");
var message="";
var imgCount=0;
var alreadyExist=false;
try{
if (IsPost && Request.Files.Count > 0) {
bool deleteSuccess = false;
var fileName = "";
var photoName = "";
var fileSavePath = "";
var uploadedFile = Request.Files[0];
var toDelete=Request["toDelete"];
var toUpload=Request["toUpload"];
if(uploadedFile.ContentLength>0){
#******************DELETE***************#
var fullPath = Server.MapPath("~/img/" + toDelete);
if (File.Exists(fullPath))
{
File.Delete(fullPath);
deleteSuccess = true;
}
#****************UPLOAD*******************#
fileName = Path.GetFileName(uploadedFile.FileName);
fileSavePath = Server.MapPath("~/img/" +
fileName);
uploadedFile.SaveAs(fileSavePath);
var updateQuery="Update Contents Set "+toUpload +"=#0";
db.Execute(updateQuery, fileName);
//Response.Redirect("editMode.cshtml");
}
}
}
catch(HttpException ex){
message="Image size you selected was too large. Please select a different Image.";
}

Try changing the permission of the folder to 777.

Related

cannot read property "0" of undefined error

I have a code that pulls information from all excel type files in some folders on google drive. The problem is that there are over 100 files and the code only pulls data from around 30 files and shows the following error: "TypeError: Cannot read property '0' of undefined" The error is in line 12, "console.log(lista_carpetas_ok2[i][0]) // Here, you can see the folder ID in the log."
function listfechas() {
var ss2 = SpreadsheetApp.getActiveSpreadsheet();
var carpetasSheet = ss2.getSheetByName("carpetas");
var lista_carpetas = carpetasSheet.getRange("C2:C" + carpetasSheet.getLastRow()).getValues();
var lista_carpetas_ok2 = lista_carpetas.filter(([a]) => a);
var sheet2 = ss2.getSheetByName("SS23");
sheet2.clear();
sheet2.appendRow(["Folder", "Name", "SMS","rec SMS", "FIT", "rec FIT", "2FIT", "rec 2FIT" ,"3FIT" ,"rec 3FIT" ,"PP" ,"rec PP" ,"2PP" ,"rec 2PP", "3PP", "rec 3PP","SHIP", "rec SHIP", "2SHIP","rec 2SHIP"]);
for (var i = 0; i < 5; i++) {
console.log(lista_carpetas_ok2[i][0]) // Here, you can see the folder ID in the log.
var folderid = lista_carpetas_ok2[i][0];
try {
var parentFolder =DriveApp.getFolderById(folderid);
listFiles(parentFolder,parentFolder.getName())
listSubFolders(parentFolder,parentFolder.getName());
} catch (e) {
Logger.log(e.toString());
}
}
function listSubFolders(parentFolder,parent) {
var childFolders = parentFolder.getFolders();
while (childFolders.hasNext()) {
var childFolder = childFolders.next();
Logger.log("Fold : " + childFolder.getName());
listFiles(childFolder,parent)
listSubFolders(childFolder,parent + "|" + childFolder.getName());
}
}
function listFiles(fold,parent){
var data = [];
var files = fold.getFilesByType(MimeType.GOOGLE_SHEETS);
try {
while (files.hasNext()) {
var file = files.next();
var sms = SpreadsheetApp.open(file).getSheetByName("fechas").getRange("A2").getValue();
var recsms = SpreadsheetApp.open(file).getSheetByName("fechas").getRange("B2").getValue();
var fit = SpreadsheetApp.open(file).getSheetByName("fechas").getRange("C2").getValue();
var recfit = SpreadsheetApp.open(file).getSheetByName("fechas").getRange("D2").getValue();
var dfit = SpreadsheetApp.open(file).getSheetByName("fechas").getRange("E2").getValue();
var recdfit = SpreadsheetApp.open(file).getSheetByName("fechas").getRange("F2").getValue();
var tfit = SpreadsheetApp.open(file).getSheetByName("fechas").getRange("G2").getValue();
var rectfit = SpreadsheetApp.open(file).getSheetByName("fechas").getRange("H2").getValue();
var pp = SpreadsheetApp.open(file).getSheetByName("fechas").getRange("I2").getValue();
var recpp = SpreadsheetApp.open(file).getSheetByName("fechas").getRange("J2").getValue();
var dpp = SpreadsheetApp.open(file).getSheetByName("fechas").getRange("K2").getValue();
var recdpp = SpreadsheetApp.open(file).getSheetByName("fechas").getRange("L2").getValue();
var tpp = SpreadsheetApp.open(file).getSheetByName("fechas").getRange("M2").getValue();
var rectpp = SpreadsheetApp.open(file).getSheetByName("fechas").getRange("N2").getValue();
var ship = SpreadsheetApp.open(file).getSheetByName("fechas").getRange("O2").getValue();
var recship = SpreadsheetApp.open(file).getSheetByName("fechas").getRange("P2").getValue();
var dship = SpreadsheetApp.open(file).getSheetByName("fechas").getRange("Q2").getValue();
var recdship = SpreadsheetApp.open(file).getSheetByName("fechas").getRange("R2").getValue();
var fullRange = sheet2.getRange("A1:Z1001");
fullRange.setVerticalAlignment(DocumentApp.VerticalAlignment.TOP);
data = [
fold.getName(),
file.getName(),
sms,
recsms,
fit,
recfit,
dfit,
recdfit,
tfit,
rectfit,
pp,
recpp,
dpp,
recdpp,
tpp,
rectpp,
ship,
recship,
dship,
recdship,
];
sheet2.appendRow(data);
};
} catch (e) {
// In this modification, when your folder ID cannot be used, that folder ID is skipped. At that time, an error message can be seen in the log.
console.log(e.message);
}
}
}
When I wrote the code, I added catch (e) which I thought skipped the folder if there was no excel file in that folder, but the code stops at folder "QM0201" which does not have an excel file in it.
Does anybody know how I can fix it? I would like the code to run even if some folders don't have an excel files in them, those should just be skipped.
Thank you so much in advance! Any help is appreciated.
To avoid the error, replace
for (var i = 0; i < 5; i++) {
by
for (var i = 0; i < lista_carpetas_ok2.length; i++) {
This might also help to avoid the code to stop at certain folder.
Regarding the error
> Info Cannot read property 'getRange' of null"
This occurs because the spreadsheet hasn't a sheet named fechas
to avoid this error you might add
if(!SpreadsheetApp.open(file).getSheetByName("fechas")) break;
above of
var sms = SpreadsheetApp.open(file).getSheetByName("fechas").getRange("A2").getValue();
if(
Debugging tips:
To verify that the correct values are assigned to lista_carpetas_ok2, add console.log(JSON.stringify(lista_carpetas_ok2)); just below lista_carpetas_ok2 declaration so you can review the values assigned to the variable.
To have more informative logs when an error occurs, instead of
} catch (e) {
Logger.log(e.toString()); // or console.log(e.message);
}
use
} catch (e) {
console.log(e.message, e.stack);
}
This is hardly a cause of the error but who knows, the code has the very unefficient part — 72 calls to the server. It can be greatly improved if you change this:
var sms = SpreadsheetApp.open(file).getSheetByName("fechas").getRange("A2").getValue();
var recsms = SpreadsheetApp.open(file).getSheetByName("fechas").getRange("B2").getValue();
var fit = SpreadsheetApp.open(file).getSheetByName("fechas").getRange("C2").getValue();
var recfit = SpreadsheetApp.open(file).getSheetByName("fechas").getRange("D2").getValue();
var dfit = SpreadsheetApp.open(file).getSheetByName("fechas").getRange("E2").getValue();
var recdfit = SpreadsheetApp.open(file).getSheetByName("fechas").getRange("F2").getValue();
var tfit = SpreadsheetApp.open(file).getSheetByName("fechas").getRange("G2").getValue();
var rectfit = SpreadsheetApp.open(file).getSheetByName("fechas").getRange("H2").getValue();
var pp = SpreadsheetApp.open(file).getSheetByName("fechas").getRange("I2").getValue();
var recpp = SpreadsheetApp.open(file).getSheetByName("fechas").getRange("J2").getValue();
var dpp = SpreadsheetApp.open(file).getSheetByName("fechas").getRange("K2").getValue();
var recdpp = SpreadsheetApp.open(file).getSheetByName("fechas").getRange("L2").getValue();
var tpp = SpreadsheetApp.open(file).getSheetByName("fechas").getRange("M2").getValue();
var rectpp = SpreadsheetApp.open(file).getSheetByName("fechas").getRange("N2").getValue();
var ship = SpreadsheetApp.open(file).getSheetByName("fechas").getRange("O2").getValue();
var recship = SpreadsheetApp.open(file).getSheetByName("fechas").getRange("P2").getValue();
var dship = SpreadsheetApp.open(file).getSheetByName("fechas").getRange("Q2").getValue();
var recdship = SpreadsheetApp.open(file).getSheetByName("fechas").getRange("R2").getValue();
To this:
var values = SpreadsheetApp.open(file).getSheetByName("fechas").getRange('A2:R2').getValues().flat();
var [sms,recsms,fit,recfit,dfit,recdfit,tfit,rectfit,pp,recpp,dpp,recdpp,tpp,rectpp,ship,recship,dship,recdship] = values;
It will reduce the quantity of calls to 4!
It should work faster and, if the real cause of the error is exceed of time limit (~6 min) this improvement can help. Try it.
Probably you could simplify the code further. Instead of this:
data = [
fold.getName(),
file.getName(),
sms,
recsms,
fit,
recfit,
dfit,
recdfit,
tfit,
rectfit,
pp,
recpp,
dpp,
recdpp,
tpp,
rectpp,
ship,
recship,
dship,
recdship,
];
You can use this:
var values = SpreadsheetApp.open(file).getSheetByName("fechas").getRange('A2:R2').getValues().flat();
var data = [fold.getName(), file.getName(), ...values];
No need to use the 18 variables, as far as I can see. It barely affects on the speed, though.

Image in ASP.NET MVC

I have form for upload file and i want to upload thumbnail for the file in the same form I am doing that with this part of code :
var basePath2 = Path.Combine(Directory.GetCurrentDirectory() + "\\Thumbnails\\");
bool basePathExists2 = System.IO.Directory.Exists(basePath2);
if (!basePathExists2)
Directory.CreateDirectory(basePath2);
var thumbnailPath = Path.Combine(basePath2, Thumbnail.FileName);
if (!System.IO.File.Exists(thumbnailPath))
{
using (var stream = new FileStream(thumbnailPath, FileMode.Create))
{
await Thumbnail.CopyToAsync(stream);
}
}
I am saving this model to the database:
var fileModel = new FileUploadViewModel
{
Year = createdOn,
PublishedOn = model.PublishedOn,
FileType = File.ContentType,
Extension = extension,
Name = model.Name,
Description = model.Description,
FilePath = filePath,
Author = model.Author,
ThumbnailPath = thumbnailPath,
};
When I want to show the thumbnail in a view, it doesn't work but in src I have the right path, as you can see in this screenshot:
Screenshot with Source of image
In controller :
string uniqueThumbName = null;
if (Thumbnail != null)
{
string uploadsFolder = Path.Combine(hostingEnvironment.WebRootPath, "Thumbnails");
uniqueThumbName=Guid.NewGuid().ToString() + "_" + Thumbnail.FileName;
string filePath2 = Path.Combine(uploadsFolder, uniqueThumbName);
Thumbnail.CopyTo(new FileStream(filePath2, FileMode.Create));
}
var fileModel = new FileUploadViewModel
{
ThumbnailPath=uniqueThumbName,
};
In View :
var thumbPath = "~/Thumbnails/" + file.ThumbnailPath;
<img style="width:80px;height:80px;" src="#thumbPath" asp-append-version="true" />

How to save image path in database and save image in specific folder of project.NET core

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create(Employee emp)
{
if (ModelState.IsValid)
{
var files = HttpContext.Request.Form.Files;
foreach (var Image in files)
{
if (Image != null && Image.Length > 0)
{
var file = Image;
var root = _appEnvironment.WebRootPath;
var uploads = "uploads\\img";
if (file.Length > 0)
{
// you can change the Guid.NewGuid().ToString().Replace("-", "")
// to Guid.NewGuid().ToString("N") it will produce the same result
var fileName = Guid.NewGuid().ToString("N") + Path.GetExtension(file.FileName);
using (var fileStream = new FileStream(Path.Combine(root, uploads, fileName), FileMode.Create))
{
await file.CopyToAsync(fileStream);
// This will produce uploads\img\fileName.ext
emp.ImageUrl = Path.Combine(uploads, fileName);
}
}
}
}
db.Add(emp);
await db.SaveChangesAsync();
return RedirectToAction("Index");
}
else
{
var errors = ModelState.Values.SelectMany(v => v.Errors);
}
return View(emp);
}
HTML
<input asp-for="ImageUrl" type="file" Class="form-control" />
when i save image, image save successfully in database, but it takes full image path like this C:\Users\VIZO\Desktop\employee.jpg i dont want like this, i need to save image path something like this ~images\employee.jpg. The other problem is image doesnt saving in specific folder of project, i need to save image in this path of my project
uploads\img
So basically your _appEnvironment.WebRootPath by default will be:
%PathToProject%/wwwroot.
For the filePath on your database i would do something like this:
var root = _appEnvironment.WebRootPath
var uploads = "uploads\\img";
if (file.Length > 0)
{
// you can change the Guid.NewGuid().ToString().Replace("-", "")
// to Guid.NewGuid().ToString("N") it will produce the same result
var fileName = Guid.NewGuid().ToString("N") + Path.GetExtension(file.FileName);
using (var fileStream = new FileStream(Path.Combine(root, uploads, fileName), FileMode.Create))
{
await file.CopyToAsync(fileStream);
// This will produce uploads\img\fileName.ext
emp.BookPic = Path.Combine(uploads, fileName);
}
}
If you require any more clarification or guidance please feel free to comment and allow me to explain in more detail.
Thanks.

Android post image to Facebook comment

This is a followup to my previous question: Xamarin.Forms App return data to calling App
That works perfectly and I can share images to anywhere, except to Facebook comments. When I click the camera on the content box the app can be selected, I can select the image, Set result and Finish are called, and the app closes and it sends data to Facebook, and then however I then get the error : The image could not be uploaded, try again?
I can't find any fundamental differences between posting to a status or a comment, so I'm guessing it's subtle. Any thoughts on how I can change my intent to post properly?
Adding for completeness:
Bitmap b = null;
string url;
if (!string.IsNullOrEmpty(this.saleItems[i].ImageUrl))
{
url = this.saleItems[i].ImageUrl;
}
else
{
url = await FileHelper.GetLocalFilePathAsync(this.saleItems[i].Id);
}
//download
using (var webClient = new WebClient())
{
var imageBytes = webClient.DownloadData(url);
if (imageBytes != null && imageBytes.Length > 0)
{
b = BitmapFactory.DecodeByteArray(imageBytes, 0, imageBytes.Length);
}
}
//set local path
var tempFilename = "test.png";
var sdCardPath = Android.OS.Environment.ExternalStorageDirectory.AbsolutePath;
var filePath = System.IO.Path.Combine(sdCardPath, tempFilename);
using (var os = new FileStream(filePath, FileMode.Create))
{
b.Compress(Bitmap.CompressFormat.Png, 100, os);
}
b.Dispose();
var imageUri = Android.Net.Uri.Parse($"file://{sdCardPath}/{tempFilename}");
var sharingIntent = new Intent();
sharingIntent.SetAction(Intent.ActionSend);
sharingIntent.SetType("image/*");
sharingIntent.PutExtra(Intent.ExtraText, "some txt content");
sharingIntent.PutExtra(Intent.ExtraStream, imageUri);
sharingIntent.AddFlags(ActivityFlags.GrantReadUriPermission);
//await SaleItemDataService.Instance.BuySaleItemAsync(this.saleItem);
SetResult(Result.Ok, sharingIntent);
Finish();
Use below:
Intent sharingIntent = new Intent();
string imageUri = "file://" + requestedUri;
sharingIntent.SetData(Android.Net.Uri.Parse(imageUri));

How do I fix charset problems in .gs script?

I have a problem with charsets.
I parsed a csv file in google-app-engine and I'm posting to an uiapp table.
But I checked special characters like áéíóú and those are not well displayed (?square symbol).
When I was setting up my code I played writing the string imported to a google docs document and it worked the same.
some advice please?
I search for:
a global charset definition to the code. or
string var transformation that makes the chars appear like I want to. (avoiding html &number definitions.
Is this related to the blob object?
The thing is important i come from spain and we need such characters.
app that get's a csv ';' delimited file and shows it's content
I post all my code, it's barely as the tutorial that is given.
function arreglaUrl(cadena){
var texto = cadena[cadena.length - 2]
if (texto == ''){
cadena[cadena.length - 2] = 'Sin enlace';
}
else{
cadena[cadena.length - 2] = '<center>Link.</center>' ;
};
}
function parsedCSV(){
var listaArchivos = DocsList.getFolderById('XXXXX').getFiles()
for (var i = 0; i < listaArchivos.length; i++) {
if (listaArchivos[i].getName() == 'baul.csv'){
var origen = listaArchivos[i];
};
}
var texto = origen.getContentAsString();
var arra = Utilities.parseCsv(texto,";");
return(arra);
}
function doGet() {
var datos = parsedCSV()
var baul = Charts.newDataTable()
for (i = 0; i < datos[0].length; i++){
baul.addColumn(Charts.ColumnType.STRING, datos[0][i])
}
for (i = 1; i < datos.length; i++){
arreglaUrl(datos[i]) // this only makes some html i need to post some links
baul.addRow(datos[i])
}
baul.build();
var sectorFilter = Charts.newCategoryFilter()
.setFilterColumnLabel("sector")
.build();
var tipoFilter = Charts.newCategoryFilter()
.setFilterColumnLabel("tipo")
.build();
var searchFilter = Charts.newStringFilter()
.setFilterColumnLabel("Titulo")
.build();
var searchDesc = Charts.newStringFilter()
.setFilterColumnLabel("descripcion")
.build();
var tableChart = Charts.newTableChart().setOption('allowHtml', true).setDimensions(0,0)
.build();
var dashboard = Charts.newDashboardPanel()
.setDataTable(baul)
.bind([sectorFilter, tipoFilter, searchFilter, searchDesc], [tableChart])
.build();
var uiApp = UiApp.createApplication().setTitle('Baul de Recursos');
var anchoTotal = '100%';
dashboard.add(uiApp.createVerticalPanel()
.add(uiApp.createHorizontalPanel()
.add(sectorFilter)
.add(tipoFilter)
.setSpacing(15)
)
.add(uiApp.createHorizontalPanel()
.add(searchFilter)
.add(searchDesc)
.setSpacing(15)
)
.add(uiApp.createHorizontalPanel()
.add(tableChart).setBorderWidth(1).setHorizontalAlignment(UiApp.HorizontalAlignment.CENTER).setWidth(anchoTotal)
)
);
uiApp.add(dashboard);
return uiApp;
}
I found it, we need to get the content of the file first with a Blob object.
This function is the one I use to parse some csv info into an array:
function parsedCSV(){
//searching the file. This gets only one file in var origen
var listaArchivos = DocsList.getFolderById('XXXXXXX').getFiles()
for (var i = 0; i < listaArchivos.length; i++) {
if (listaArchivos[i].getName() == 'baul.csv'){
var origen = listaArchivos[i];
};
}
// HERE IS THE GOOD DEFINITION OF CHAR:
var texto2= origen.getBlob().getDataAsString('ISO-8859-1');
// I put all the corrected text in an array
var arra = Utilities.parseCsv(texto2,";");
return(arra);
}
This is the solved thing: https://script.google.com/macros/s/AKfycbyHa-bLWBHBr3qifbvzxecqGgGUYX8mhyo-TKoyfGvy/exec
The trick:
var textVariableName = fileObjectVariableName.getBlob().getDataAsString('ISO-8859-1');

Resources