GoogleDrive picker downloading login page content - google-drive-realtime-api

I am using Google Drive Picker in my project.The file is downloading but downloaded file contains the login page content.
using (System.Net.WebClient client = new System.Net.WebClient())
{if (fileName != null)
{var saveFolder = Path.Combine(ConfigurationManager.AppSettings["TempUploadDir"],Guid.NewGuid().ToString());
if (!Directory.Exists(saveFolder))
{
Logger.LogTrace("Attempting to create folder:" + saveFolder);
Directory.CreateDirectory(saveFolder);
}
path = Path.Combine(saveFolder, fileName);
Logger.LogTrace("Saving uploaded document to local Path:" + path);
if (System.IO.File.Exists(path))
{
System.IO.File.Delete(path);
}
client.DownloadFile(new Uri(urlAddress), path);
}
}

Related

React-Flask download excel file with button click

I'm trying to download an excel file with the click of a button in my web application. I can see the data come across from my api request, but when I download the file and try to open it I either get a:
"We found a problem with some content in ... Do you want us to try to recover as much as possible" YES => "This file is corrupt and cannot be opened"
or
"... the file format or file extension is not valid. Verify that theh file has not been corrupted..."
If I open the original file saved it works fine so it's not the file. I think the problem is somewhere in the React Code.
I've looked at a lot of other questions on Stack Overflow about this same topic but none of the answers seem to be working for me.
React
React.useEffect(() => {
if (template && downloadBtn.current != null) {
axios
.get<Blob>(
`/template`,
{ params: { filename: template } }
// responseType: 'blob' or "arraybuffer" don't work for me
)
.then((resp) => {
console.log(resp.data);
var blob = new Blob([resp.data], {
type: resp.headers['content-type'] // tried keeping and removing this
}); // removing this assuming resp.data is already a blob didn't work
console.log(blob); // PK ... b���C���h����ؒ )���G+N�
const url = window.URL.createObjectURL(blob);
console.log(url); // blob:http://localhost:3000/29fd5f64-da6a-4b9c-b4a4-76cce1d691c8
if (downloadBtn.current != null) {
downloadBtn.current.download = template;
downloadBtn.current.href = url;
}
});
}
}, [template, downloadBtn.current]);
Flask
#app.route('/template', methods=['GET'])
def template():
filename = getRouteData(['filename']) # helper function I wrote to get request.body data
print(os.path.join(
app.config['templates_folder'], filename), file=sys.stderr)
return send_file(os.path.join(app.config['templates_folder'], filename))
# adding as_attachment=True doesn't work for me either
# file path is correct

Extracting zipped files using JSZIP in javascript not working on IE11

In my webpage, a user is supposed to upload a zipped file. Within the zipped file are multiple xlsx files. I am using below code for reading ZIP file , It works great on Chrome but when I am trying to run on IE11 it says, could not find resolve for null object or reference
var JSZip = require('JSZip');
fs.readFile{ filePath, function(err, data) {
if (!err) {
var zip = new JSZip();
zip.loadAsync(data).then(function(contents) {
Object.keys(contents.files).forEach(function(filename) {
zip.file(filename).async('nodebuffer').then(function(content) {
var dest = path + filename;
fs.writeFileSync(dest, content);
});
});
});
}
});
When I try to debug it is not going inside loadAync function.

How to view a file located on server on click of a button?

I'm passing an Id on click of a button(button is in 192.xxx.x.xxx\Profile\Details page) to angularJS controller file where it is calling an API
$scope.docView = function () {
Method.getbyId("api call",docId).then(function(response) {
if (response.data.message != null)
window.open('//'+response.data.message);
else
alert("File Not Found !");
}).catch(function (data) {
console.log("Unknown Error");
});
}
}
API is :
[Route("api call")]
[HttpGet]
public IHttpActionResult ViewDocument (Guid? docId)
{
/*background work*/
response.Message = filePath;
}
}
catch (Exception ex)
{
Utils.Write(ex);
}
return Ok(response);
}
In response.data.message, the path of the file(192.xxx.x.xxx\folder\filename) on the server is coming which will open the file via window.open(). But in URL, whole path of the folder is visible which will become security breach. Hence I want to 'display the file in a new View' in the same controller which will open the file in a new tab. The url should be like (192.xxx.x.xxx\Profile\Details? docid=xxxxxxxxxxxxxxxxx ).
What you are actually looking for, you can find with a quick search on Google:
"Download file from an ASP.NET Web API method".
For example
here and
here you'll find examples which implement what you are looking for.
EDIT:
HttpResponseMessage response = new HttpResponseMessage();
response.StatusCode = HttpStatusCode.OK;
response.Content = new StreamContent(result);
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue(System.Net.Mime.DispositionTypeNames.Inline)
{
FileName = "foo.pdf"
};
result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");
As derived from this and this Thread.
You would need to change the Content-Type according to the actual file type. Also if the file is actually viewable inside the Browser depends on wether the Browser is able to do so.

Save image offline using sqlite Ionic App

I am working on ionic project which needs to work offline. My issue is, how to save uploaded image offline in sqlite database, and when track any wifi connection, synch to online.
Image uploading online is working fine, using cordova camera plugin and filetransfer plugin.
You can use cordova file plugin's copyfile method to store the image locally, and then save its link in the database for further use. When the wifi is detected, just use that link to upload file to server with same cordovafile plugin.
$cordovaCamera.getPicture(options).then(function(sourcePath) { //for capturing image
console.log(sourcePath);
var sourceDirectory = sourcePath.substring(0, sourcePath.lastIndexOf('/') + 1); //image file with path url
var sourceFileName = sourcePath.substring(sourcePath.lastIndexOf('/') + 1, sourcePath.length); //image name
console.log("Copying from : " + sourceDirectory + sourceFileName);
console.log("Copying to : " + cordova.file.dataDirectory + sourceFileName);
//used to store file locally
$cordovaFile.copyFile(sourceDirectory, sourceFileName,
cordova.file.dataDirectory, sourceFileName).then(function(success) {
$scope.fileName = cordova.file.dataDirectory + sourceFileName;
console.log($scope.fileName, success);
$scope.propic = $scope.fileName;
}, function(error) {
console.log(error);
});
}, function(err) {
console.log(err);
});

Not allowed to load local resource

Currently i am running one MVC 5 project with web api where i am using angular js ajax call to fire web api method and get image path but when i am setting that path in img tag so image is not displaying and in chrome console message displays that not able to load local resource.
Below is the web api method code which i am calling through ajax
[Route("Files")]
public List<FilesInfo> GetImages()
{
rootPath = HostingEnvironment.MapPath("~/Content/Images/");
List<FilesInfo> files = new List<FilesInfo>();
foreach (var item in Directory.GetFiles(rootPath))
{
FileInfo f = new FileInfo(item);
files.Add(new FilesInfo(){FileName=f.Name, FilePath=rootPath+f.Name});
}
return files;
}
Please let me know if you have any queries.
It seems HostingEnvironment.MapPath returns the physical path on the server.
When you are adding this path to the src attribute of your img, the browser complains it cannot local local resource.
You'd need to adjust the path to the image to be relative to your site: /img/img1.jpg
Try:
[Route("Files")]
public List<FilesInfo> GetImages()
{
rootPath = "/Content/Images/";
List<FilesInfo> files = new List<FilesInfo>();
foreach (var item in Directory.GetFiles(HostingEnvironment.MapPath("~"+ rootPath);))
{
FileInfo f = new FileInfo(item);
files.Add(new FilesInfo() { FileName = f.Name, FilePath = rootPath + f.Name });
}
return files;
}
This way System.IO.FileInfo should have the local path, and your FilesInfo should have the relative url path, which you can use with angular to create your: <img ng-src="{{vm.file.filePath}}" alt="{{vm.file.fileName}}" />

Resources