I'm using uploadify in my MVC3 project. It works fine to upload multiple files and saving to folders as well.
How to pass the path of the uploaded file to controller action ? -- I need to pass it to the ExtractingZip action of my controller.
To extract the contents of the .zip file, I'm using DotNetZip Library.
Here is what i've tried so far.
$('#file_upload').uploadify({
'checkExisting': 'Content/uploadify/check-exists.php',
'swf': '/Content/uploadify/uploadify.swf',
'uploader': '/Home/Index',
'auto': false,
'buttonText': 'Browse',
'fileTypeExts': '*.jpg;*.jpeg;*.png;*.gif;*.zip',
'removeCompleted': false,
'onSelect': function (file) {
if (file.type == ".zip") {
debugger;
$.ajax({
type: 'POST',
dataType: 'json',
url: '#Url.Action("ExtractingZip", "Home")',
data: ({ fileName: file.name}), // I dont see a file.path to pass it to controller
success: function (result) {
alert('Success');
},
error: function (result) {
alert('error');
}
});
}
}
});
Here is my controller action:
[HttpPost]
public ActionResult ExtractingZip(string fileName,string filePath, HttpPostedFileBase fileData)
{
string zipToUnpack = #"C:\Users\Public\Pictures\Sample Pictures\images.zip";// I'm unable to get the filePath so i'm using the path.
string unpackDirectory = System.IO.Path.GetTempPath();
using (ZipFile zip1 = ZipFile.Read(zipToUnpack))
{
// here, we extract every entry, but we could extract conditionally
// based on entry name, size, date, checkbox status, etc.
var collections = zip1.SelectEntries("name=*.jpg;*.jpeg;*.png;*.gif;");
foreach (var item in collections)
{
item.Extract(unpackDirectory, ExtractExistingFileAction.OverwriteSilently);
}
}
return Json(true);
}
[HttpPost]
public ActionResult Index(IEnumerable<HttpPostedFileBase> fileData)
{
foreach (var file in fileData)
{
if (file.ContentLength > 0)
{
string currpath;
currpath = Path.Combine(Server.MapPath("~/Images/User3"), file.FileName);
//save to a physical location
file.SaveAs(currpath);
}
}
}
You don't need to pass the zip's filepath when it's uploaded. The filepath would be from the clients machine right? Your application on your server has no knowledge or access to the clients file system.
The good news is you don't need it. You already have the contents of your file in memory. I have never used donetzip but some quick googling reveals that you can read zips directly from a stream.
Check out these links:
Cannot read zip file from HttpInputStream using DotNetZip 1.9
Extracting zip from stream with DotNetZip
So using those posts as a base to go off of... It looks like you should be able to change your code like so:
string zipToUnpack = #"C:\Users\Public\Pictures\Sample Pictures\images.zip";// I'm unable to get the filePath so i'm using the path.
string unpackDirectory = System.IO.Path.GetTempPath();
using (ZipFile zip1 = ZipFile.Read(zipToUnpack))
{
....
Changes to...
string unpackDirectory = System.IO.Path.GetTempPath();
using (ZipFile zip1 = ZipFile.Read(fileData.InputStream))
{
....
Let me know if that helps.
First of, due to security reasons you have no access directly to clients machine. While a user uploads some files, web browsers make one or tow (usually 1, according to RFC) stream and server-side script reads that stream, so do not waste your time to get files directly from user's local machine's filepath.
To extract archives (s.a: Zip, Rar) I highly recommend you to use SevenZipSharp. It works really good and easy with Streams and also many compression formats.
As they documentation you can extract stream like this:
using (MemoryStream msin = new MemoryStream(fileData.InputStream))
{ ... }
Related
My model is held in a JavaScript object on the client side, where the user can edit its properties via the UI controls. I want to offer the user an option to download a JSON file representing the model they're editing. I'm using MVC core with .net 6.
What I've tried
Action method (using Newtonsoft.Json to serialize the model to JSON):
public IActionResult Download([FromForm]SomeModel someModel)
{
var json = JsonConvert.SerializeObject(someModel);
var characters = json.ToCharArray();
var bytes = new byte[characters.Length];
for (var i = 0; i < characters.Length; i++)
{
bytes[i] = (byte)characters[i];
}
var stream = new MemoryStream();
stream.Write(bytes);
stream.Position = 0;
return this.File(stream, "APPLICATION/octet-stream", "someFile.json");
}
Code in the view to call this method:
<button class="btn btn-primary" onclick="download()">Download</button>
And the event handler for this button (using jQuery's ajax magic):
function download() {
$.ajax({
url: 'https://hostname/ControllerName/Download',
method: 'POST',
data: { someModel: someModel },
success: function (data) {
console.log('downloading', data);
},
});
}
What happened
The browser console shows that my model has been posted to the server, serialized to JSON and the JSON has been returned to the browser. However no file is downloaded.
Something else I tried
I also tried a link like this to call the action method:
#Html.ActionLink("Download", "Download", "ControllerName")
What happened
This time a file was downloaded, however, because ActionLink can only make GET requests, which have no request body, the user's model isn't passed to the server and instead the file which is downloaded represents a default instance of SomeModel.
The ask
So I know I can post my model to the server, serialize it to JSON and return that JSON to the client, and I know I can get the browser to download a JSON-serialized version of a model, but how can I do both in the same request?
Edit: What I've done with the answer
I've accepted Xinran Shen's answer, because it works as-is, but because I believe that just copying code from Stack Overflow without understanding what it does or why isn't good practice, I did a bit of digging and my version of the saveData function now looks like this:
function saveData(data, fileName) {
// Convert the data to a JSON string and store it in a blob, a file-like
// object which can be downloaded without it existing on the server.
// See https://developer.mozilla.org/en-US/docs/Web/API/Blob
var json = JSON.stringify(data);
var blob = new Blob([json], { type: "octet/stream" });
// Create a URL from which the blob can be downloaded - see
// https://developer.mozilla.org/en-US/docs/Web/API/URL/createObjectURL
var url = window.URL.createObjectURL(blob);
// Add a hidden hyperlink to the page, which will download the file when clicked
var a = document.createElement("a");
a.style = "display: none";
a.href = url;
a.download = fileName;
document.body.appendChild(a);
// Trigger the click event on the hyperlink to download the file
a.click();
// Release the blob's URL.
// Browsers do this when the page is unloaded, but it's good practice to
// do so as soon as it's no longer needed.
window.URL.revokeObjectURL(url);
// Remove the hidden hyperlink from the page
a.remove();
}
Hope someone finds this useful
First, Your code is right, You can try to access this method without ajax, You will find it can download file successfully,But You can't use ajax to achieve this, because JavaScript cannot interact with disk, you need to use Blob to save the file. change your javascript like this:
function download() {
$.ajax({
url: 'https://hostname/ControllerName/Download',
method: 'Post',
data: { someModel: someModel },,
success: function (data) {
fileName = "my-download.json";
saveData(data,fileName)
},
});
}
var saveData = (function () {
var a = document.createElement("a");
document.body.appendChild(a);
a.style = "display: none";
return function (data, fileName) {
var json = JSON.stringify(data),
blob = new Blob([json], {type: "octet/stream"}),
url = window.URL.createObjectURL(blob);
a.href = url;
a.download = fileName;
a.click();
window.URL.revokeObjectURL(url);
};
}());
I think you may need FileStreamResult, also you need to set the MIME type to text file or json file.
// instead of this
return this.File(stream, "APPLICATION/octet-stream", "someFile.json");
// try this
return new FileStreamResult(stream, new MediaTypeHeaderValue("text/plain"))
{
FileDownloadName = "someFile.txt"
};
// or
return new FileStreamResult(stream, new MediaTypeHeaderValue("application/json"))
{
FileDownloadName = "someFile.json"
};
Reference: https://www.c-sharpcorner.com/article/fileresult-in-asp-net-core-mvc2/
I'm processing a table of banking/statement entries that have been exported from another system via a CSV file. They are imported into a view and checked for duplicates before being presented to the user in a HTML table for final review.
Once checked they are sent via AJAX to the server so they can be added into a Django model. Everything is working OK including CSRF but I cannot access the POSTed variable although I can see it!
Unfortunately making a hidden form isn't viable as there are 80+ rows to process.
My Javascript looks like:
$.ajax({
type: 'POST',
url: '......./ajax/handleImports/',
data: entriesObj,
success: function (data) {
if (data.response && data.response) {
console.log("Update was successful");
console.log(data.entries)
} else { ... }
},
error: function() { ... }
where entriesObj is
var entriesObj = JSON.stringify({ "newentries": newEntries });
console.log(entriesObj)
and when dumped to console.log looks like:
{"newentries":[{"Include":"","Upload ID":"0","Date":"2019-01-09", ... }
Now in view.py when I return the whole request.POST object as data.entries using
context['entries'] = request.POST
return JsonResponse(context)
I get
{"{"newentries":[{"Include":"","Upload ID":"0","Date":"2019-01-09", ... }
but if I try and retrieve newentries with:
entries = request.POST.get('newentries', None)
context['entries'] = entries
return JsonResponse(context)
the console.log(data.entries) will output null?
How am I supposed to access the POSTed entriesObj?
The data is JSON, you need to get the value from request.body and parse it.
data = json.loads(request.body)
entries = data.get('newentries')
I'm working on a Cloud Code function that uses facebook graph API to retrieve users profile picture. So I have access to the proper picture URL but I'm not being able to acreate a Parse.File from this URL.
This is pretty much what I'm trying:
Parse.Cloud.httpRequest({
url: httpResponse.data["attending"]["data"][key]["picture"]["data"]["url"],
success: function(httpImgFile)
{
var imgFile = new Parse.File("file", httpImgFile);
fbPerson.set("profilePicture", imgFile);
},
error: function(httpResponse)
{
console.log("unsuccessful http request");
}
});
And its returning the following:
Result: TypeError: Cannot create a Parse.File with that data.
at new e (Parse.js:13:25175)
at Object.Parse.Cloud.httpRequest.success (main.js:57:26)
at Object.<anonymous> (<anonymous>:842:19)
Ideas?
I was having trouble with this exact same problem right now. For some reason this question is already top on Google results for parsefile from httprequest buffer!
The Parse.File documentation says
The data for the file, as 1. an Array of byte value Numbers, or 2. an Object like { base64: "..." } with a base64-encoded String. 3. a File object selected with a file upload control. (3) only works in Firefox 3.6+, Safari 6.0.2+, Chrome 7+, and IE 10+.
I believe for CloudCode the easiest solution is 2. The thing that was tripping me earlier is that I didn't notice it expects an Object with the format { base64: {{your base64 encoded data here}} }.
Also Parse.Files can only be set to a Parse.Object after being saved (this behaviour is also present on all client SDKs). I strongly recommend using the Promise version of the API as it makes much easier to compose such asynchronous operations.
So the following code will solve your problem:
Parse.Cloud.httpRequest({...}).then(function (httpImgFile) {
var data = {
base64: httpImgFile.buffer.toString('base64')
};
var file = new Parse.File("file", data);
return file.save();
}).then(function (file) {
fbPerson.set("profilePicture", file);
return fbPerson.save();
}).then(function (fbPerson) {
// fbPerson is saved with the image
});
I am trying to load sample data from a REST API source that return XML inside my emberjs app but I am facing two problems:
The model name is always in plural, so instead of /sqlrest/CUSTOMER/3/ the code always generate /sqlrest/CUSTOMERS/3/
I know that DS.RESTAdaptor expects by default JSON format so I was wondering is there any way I can still get XML format and may be convert to JSON?
Thanks
Code I am using is as follows (This code I found in one of SO replies and altered to match the URL I am trying to access):
App.store = DS.Store.create({
revision: 11,
adapter: DS.RESTAdapter.create({
namespace: "sqlrest",
url: "http://www.thomas-bayer.com",
plurals: {
'customer': 'customer'
},
ajax: function (url, type, hash) {
hash.url = url;
hash.type = type;
hash.dataType = 'jsonp';
hash.contentType = 'application/json; charset=utf-8';
hash.context = this;
if (hash.data && type !== 'GET') {
hash.data = JSON.stringify(hash.data);
}
jQuery.ajax(hash);
},
})
});
and in route:
App.CustomersRoute = Ember.Route.extend({
model: function() {
//return App.Customer.find();
//New
return App.Customer.find(18);
}
});
Maybe you could look at ember-restless which allows XML consumption:
https://github.com/endlessinc/ember-restless
For pluralization, take a look in here:
https://github.com/emberjs/data/blob/v1.0.0-beta.6/packages/ember-data/lib/adapters/rest_adapter.js#L476
The only thing is, obviously if you're going to use ember-restless, you'll need to find the relative point in there that you need to override in a similar way (if it's possible to customize endpoints).
Trying to find an XML file I can use in lieu of a look-up database table until we get our web hosting switched over to the right DB.
Can anyone refer me to an XML file with elements whose children have zipcodes, states, and cities? E.g.:
<zip code="98117">
<state>WA</state>
<city>Seattle</state>
</zip>
Or
<entry>
<zip>98117</zip>
<state>WA</state>
<city>Seattle</city>
</entry>
I'll be using LINQ in C# to query this data.
Check out this one, it provides several different free ones.
https://stackoverflow.com/questions/24471/zip-code-database
There is a free zip code database located at:
http://www.populardata.com
I believe its a .CSV file but you could convert it to a XML file quite easily.
Here is code to do city.state autofill based on a zipcode entered.
<script type="text/javascript">//<![CDATA[
$(function() {
// IMPORTANT: Fill in your client key
var clientKey = "js-9qZHzu2Flc59Eq5rx10JdKERovBlJp3TQ3ApyC4TOa3tA8U7aVRnFwf41RpLgtE7";
var cache = {};
var container = $("#example1");
var errorDiv = container.find("div.text-error");
/** Handle successful response */
function handleResp(data)
{
// Check for error
if (data.error_msg)
errorDiv.text(data.error_msg);
else if ("city" in data)
{
// Set city and state
container.find("input[name='city']").val(data.city);
container.find("input[name='state']").val(data.state);
}
}
// Set up event handlers
container.find("input[name='zipcode']").on("keyup change", function() {
// Get zip code
var zipcode = $(this).val().substring(0, 5);
if (zipcode.length == 5 && /^[0-9]+$/.test(zipcode))
{
// Clear error
errorDiv.empty();
// Check cache
if (zipcode in cache)
{
handleResp(cache[zipcode]);
}
else
{
// Build url
var url = "http://www.zipcodeapi.com/rest/"+clientKey+"/info.json/" + zipcode + "/radians";
// Make AJAX request
$.ajax({
"url": url,
"dataType": "json"
}).done(function(data) {
handleResp(data);
// Store in cache
cache[zipcode] = data;
}).fail(function(data) {
if (data.responseText && (json = $.parseJSON(data.responseText)))
{
// Store in cache
cache[zipcode] = json;
// Check for error
if (json.error_msg)
errorDiv.text(json.error_msg);
}
else
errorDiv.text('Request failed.');
});
}
}
}).trigger("change");
});
//]]>
Here is the API - http://www.zipcodeapi.com/Examples#example1.
You can request the content in XML via To get the data back directly in XML you can use .xml in the format in the request.
https://www.zipcodeapi.com/rest/RbdapNcxbjoCvfCv4N5iwB3L4beZg017bfiB2u9eOxQkMtQQgV9NxdyCoNCENDMZ/info.xml/90210/degrees
Will respond with
<response>
<zip_code>90210</zip_code>
<lat>34.100501</lat>
<lng>-118.414908</lng>
<city>Beverly Hills</city>
<state>CA</state>
<timezone>
<timezone_identifier>America/Los_Angeles</timezone_identifier>
<timezone_abbr>PDT</timezone_abbr>
<utc_offset_sec>-25200</utc_offset_sec>
<is_dst>T</is_dst>
</timezone>
<acceptable_city_names/>
</response>
Api docs are at https://www.zipcodeapi.com/API