File Upload using Twitter Bootstrap, C#, asp.net and javascript - c#

link to Jasny http://jasny.github.com/bootstrap/javascript.html#fileupload
link to what the form looks like http://img507.imageshack.us/img507/3308/picpx.png
I am using the Jasny Javascript file upload in my boot strap project, it looks like this:
ASP\HTML VIEW
<div class="row-fluid">
<div class="fileupload fileupload-new" data-provides="fileupload"><input type="hidden">
<div class="input-append">
<div class="uneditable-input span2" runat="server" id="statment1"><i class="icon-file
fileupload-exists"></i> <span class="fileupload-preview" style=""></span></div><span
class="btn btn-file"><span class="fileupload-new">Select file</span><span
class="fileupload-exists">Change</span><input type="file"></span><a href="#" class="btn
fileupload-exists" data-dismiss="fileupload">Remove</a>
</div>
</div>
How do I go about using this in the code behind to save the attached file to my server as I would using the C# asp.net File Upload?
In ASP.net C# I would normally do this in the code behind:
ASP.net C# CodeBehind
string filename = FileUpload1.PostedFile.FileName;
FileUpload1.PostedFile.SaveAs(Path.Combine(Server.MapPath("\\Document"),
filename).ToString());
filelocation = "Document\\" + filename;
media = "Document";
The Jasny github explains how to set the layout using bootstrap which is great as it looks really good (much better than the boring asp file upload) but How do I actually get I to post on my button click? I would really like to get this to work as I think it looks heaps nicer.

Since you want to do this without a standard asp.net control, you will have to do some of the wiring that asp.net does for you.
Make sure your input has an id. I will set it here to myFile.
<div class="row-fluid">
<div class="fileupload fileupload-new" data-provides="fileupload"><input type="hidden">
<div class="input-append">
<div class="uneditable-input span2" runat="server" id="statment1">
<i class="icon-file fileupload-exists"></i>
<span class="fileupload-preview" style=""></span>
</div>
<span class="btn btn-file"><span class="fileupload-new">Select file</span>
<span class="fileupload-exists">Change</span><input id="myFile" type="file" runat="server">
</span>
<a href="#" class="btn fileupload-exists" data-dismiss="fileupload" >Remove</a>
</div>
</div>
</div>
Your page should now have a HtmlInputFile control to your page. like this:
protected HtmlInputFile myFile;
Then you should be able to receive the file:
if (IsPostBack)
{
if (myFile.PostedFile != null)
{
// File was sent
var postedFile = myFile.PostedFile;
int dataLength = postedFile.ContentLength;
byte[] myData = new byte[dataLength];
postedFile.InputStream.Read(myData, 0, dataLength);
}
else
{
// No file was sent
}
}

Related

Force Download of MP3 in Chrome, Firefox, Safari and IE using Amazon S3

Is there a way I can force an MP3 file to download from Amazon S3.
I have a Download button in my Razor:
<td>
<a href="#t.S3PreSignedUrl" class="js_recordingDownloadButton document-link btn btn-info btn-block br2 btn-xs fs12 #Html.Raw(t.S3PreSignedUrl.IsNullOrWhiteSpace() ? "disabled" : "")" target="_blank" data-container="body" data-toggle="tooltip" title="#t.OriginalFilename" type="#t.MimeType" download>
<span class="fa fa-cloud-download fs12"></span>
</a>
</td>
Currently, when you click on it, another browser window is opened and starts to play automatically using a Modal:
<div id="js_PlayRecordingPopup" class="popup-basic mfp-with-anim modalPopup">
<div class="panel">
<div class="admin-form">
<div class="panel-heading">
<span class="panel-title">
<i class="fa fa-play"></i> Play Recording
</span>
</div>
</div>
<div class="panel-body bt0 text-center p25">
<p class="popupInfo fs12 mb5">Playing: <b class="text-info js_playingTitle"></b></p>
<p class="popupInfo fs12">Filename: <b class="text-info js_playingFileName"></b></p>
<div class="summaryBox popupSummary text-center audioContainerBox">
<audio controls controlsList="nodownload" id="audRecording">
Your browser does not support the audio element.
</audio>
</div>
</div>
<div class="panel-footer">
<div class="text-center">
<input type="button" class="btn btn-primary" value="Done" data-bind="click: function(){ var sound = document.getElementById('audRecording'); if(sound != undefined) { sound.pause(); sound.currentTime = 0; } $.magnificPopup.close(); }">
</div>
</div>
</div>
<button title="Close (Esc)" type="button" class="mfp-close" data-bind="click: function(){ var sound = document.getElementById('audRecording'); if(sound != undefined) { sound.pause(); sound.currentTime = 0; }}">×</button>
</div>
Is there a way I can set it so that if I click Download it downloads the file straight away?
This is what it looks like in the Source Code:
<td>
<a href="https:url/Audio/Recordings/TES/39e7ca51-1ac8-f395-3ae6-ff814dbde6c3/39e7ca51-e77c-65f1-c88e-47fe20f67ee1/o_1cj5s0tntp3aa1011o51tlrd8ba.mp3?X-Amz-Expires=86400&response-content-disposition=inline%3B%20filename%3Drain-01.mp3&X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIAIOHIWJAIQSFECYZQ/20180724/eu-west-1/s3/aws4_request&X-Amz-Date=20180724T104420Z&X-Amz-SignedHeaders=host&X-Amz-Signature=02a5febff28eed31646a37fea0b8da7d7bcf4b0ffe9a3365d31a0ac3f0b2cabb" class="js_recordingDownloadButton document-link btn btn-info btn-block br2 btn-xs fs12 " target="_blank" data-container="body" data-toggle="tooltip" title="rain-01.mp3" type="audio/mp3" download>
<span class="fa fa-cloud-download fs12"></span>
</a>
</td>
You can change Content-Type on the response to Content-Type: application/octet-stream. While also setting Content-Disposition: attachment; filename="filename.mp3". Make sure filename uses encoding defined in RFC 5987
I see you already have found the download attribute on HTML5 but you're not supplying a filename. It should be used like so:
<a href="pathtofile.mp3" download="filename">
You could always test this download.js written by dandavis. If that works you could reverse his code.
I worked through a solution using S3 behind CloudFront this weekend (August 2022); and, since Amazon has recently updated CloudFront functions to allow for this fairly easily, I wanted to share how I accomplished a solution, in case someone else may need it as you work through the Amazon Documentation.
How it works
Example Listen Link:
https://d111111abcdef8.cloudfront.net/audio.mp3
(plays in browser)
Example Download Link:
https://d111111abcdef8.cloudfront.net/audio.mp3?title=Custom%20Title%20for%20File
(forces download of the .mp3 file with the custom filename: Custom Title for Downloaded File.mp3)
My Solution:
Here is my custom CloudFront function's code, which you can use as an example to help you write what you need:
function handler(event) {
//This is a viewer response function.
var request = event.request;
var uri = request.uri;
var qs = request.querystring;
//console.log ('qs: ' + qs);
var response = event.response;
var headers = response.headers;
if(!qs.title) {
//console.log('No- qs title');
} else{
var title = qs.title.value;
title = decodeURIComponent(title);
title = title.split('+').join(' ');
//console.log('Yes- qs title LEN: ' + title.length);
if (uri.endsWith('.mp3')) {
var fileType = '.mp3';
var fileName = title + fileType;
//console.log('fileName: ' + fileName);
var disposition = "attachment; filename=" + fileName;
//console.log('disposition:' + disposition);
headers['content-disposition'] = { value: disposition };
}
}
return response;
}
I set up my CloudFront Distribution to have a new behavior with:
Path pattern: "*"
Origin: my S3 bucket
Cache Policy to look for and accept only the "title" key in uri query string
Origin Request Policy to also look for and accept only the "title" key in uri query string
Associated my custom CloudFront function (above) as a Viewer response function type

c# how can i check if img file exist in div class

The problem is that I can not check if there is a file on the page.
There is a code in which this image is present:
<div class="specials-block">
<a href="/ru/actions/443">
<div class="specials-block-item icons-guide ico1" data-amount="5" data-toggle="tooltip" data-html="true" data-placement="bottom" title="" data-original-title="">
</div>
</a>
<div class="specials-block-item">
<img src="data:image/gif;base64,iVBORw0KGgoAAAANSUhEUgAAAEsA......8X2F0UZvgYHv0AAAAASUVORK5CYII=">
</div>
</div>
And the code in which this image is missing:
<div class="specials-block">
<a href="/ru/actions/443">
<div class="specials-block-item icons-guide ico1" data-amount="5" data-toggle="tooltip" data-html="true" data-placement="bottom" title="" data-original-title="">
</div>
</a>
<div class="specials-block-item">
</div>
</div>
In order to check whether this image is present, I do a check:
var intelAtom = driver.FindElement(By.XPath("/html/body/div[5]/div[4]/div/div[1]/div[1]/div[5]/div[1]/div/img[#src='------------------------------']"));
if (intelAtom.Displayed)
{
MessageBox.Show("All is OK");
}
else
{
MessageBox.Show("WTF O_o , displayed enother Icon");
}
but I need to check both the presence of the image and if the img dislayed that the desired image is displayed.
Somthing like this:
if (driver.FindElement(By.XPath("/html/body/div[5]/div[4]/div/div[1]/div[1]/div[5]/div[1]/div/img")).Displayed)
{
var intelAtom = driver.FindElement(By.XPath("/html/body/div[5]/div[4]/div/div[1]/div[1]/div[5]/div[1]/div/img[#src='------------------------------']"));
if (intelAtom.Displayed)
{
MessageBox.Show("All is OK");
}
else
{
MessageBox.Show("WTF O_o , displayed enother Icon");
}
}
else
{
MessageBox.Show("WTF O_o , Icon Intel Pentium is't displayed");
}
But if I start second query, it was failed, because it didn't find img file
driver.FindElement(By.XPath("/html/body/div[5]/div[4]/div/div[1]/div[1]/div[5]/div[1]/div/img"))
.
Perhaps someone knows how to build the right query in order to determine whether the image was displayed on the page and the correct image was displayed

Using Angular 2 to return HTML from C#/.NET service

I have an existing .NET application that I want to update to use an Angular 2 front-end. There is a section of a page that has dynamic content and every time I want to get the most up-to-date content, I currently use jquery similar to this:
$.get("/Plan/Variety/VarietyList")
.done(function (data) {
PlaceReturnedData($("body"), data, "variety-list-selling");
});
The data returned is the exact HTML I need, no need to manipulate it.
How can I use Angular 2 to return this same data? I've looked around and only see how to handle JSON data, such as the example below from Angular 2's Tour of Heroes tutorial:
heroes.component.ts:
heroes: Hero[];
selectedHero: Hero;
constructor(
private router: Router,
private heroService: HeroService
) { }
getHeroes(): void {
this.heroService.getHeroes().then(heroes => this.heroes = heroes);
}
ngOnInit(): void {
console.log('initializing MenuVarietiesComponent');
this.getHeroes();
}
hero.service.ts
#Injectable()
export class HeroService {
private heroesUrl = 'app/heroes'; // URL to web api
private headers = new Headers({'Content-Type': 'application/json'});
constructor(private http: Http){ }
getHeroes(): Promise<Hero[]> {
return this.http.get(this.heroesUrl)
.toPromise()
.then(response => response.json().data as Hero[])
.catch(this.handleError);
}
}
heroes.component.html:
<ul class="heroes">
<!-- On click, execute onSelect() function and pass in the hero variable from the ngFor. Apply the "selected" class if hero & selectedHero match, remove it if they don't -->
<li *ngFor="let hero of heroes"
(click)="onSelect(hero)"
[class.selected]="hero === selectedHero">
<span class="badge">{{hero.id}}</span>
<span>{{hero.name}}</span>
<!-- We need to stop propagation so we don't trigger the onSelect() method on the <li> -->
<button class="delete" (click)="delete(hero); $event.stopPropagation()">x</button>
</li>
</ul>
How can I modify the example Angular 2 code above to handle HTML data rather than JSON data so I can take advantage of code I already have set up on the C# end? I'm guessing the *ngFor in the html is irrelevant since I probably won't need to save my data as an array and I would probably need to change the value of heroesUrl to /Plan/Variety/VarietyList, but I'm a little stuck after that.
EDIT:
Here is what the returned HTML from my controller might look like:
<div class="varietyTypeName" data-toggle="collapse" data-target="" aria-expanded="true" aria-controls="">
Greens
<i class="fa fa-angle-down arrow-toggle"></i>
</div>
<div class="collapse in collapsableArea">
<div class="varietyFamilyName">Arugula</div>
<div class="varietyName">
<a class="ajax-rep rep-main-col" href="/Plan/Selling/DetailsPPVS/5409">Astro</a>
<a href="#deleteVarietySelling" id="deleteVarietySelling_5409" class="quick-delete fa-minus-button" title="Delete" data-toggle="modal">
<i class="fa fa-minus"></i>
</a>
</div>
</div>
<div class="collapse in collapsableArea">
<div class="varietyFamilyName">Kale</div>
<div class="varietyName">
<a class="ajax-rep rep-main-col" href="/Plan/Selling/DetailsPPVS/3720">Kalettes</a>
<a href="#deleteVarietySelling" id="deleteVarietySelling_3720" class="quick-delete fa-minus-button" title="Delete" data-toggle="modal">
<i class="fa fa-minus"></i>
</a>
</div>
</div>
What you need to do is something like this:
import {Component, OnInit} from '#angular/core';
import {DomSanitizationService} from "#angular/platform-browser";
export class SideBarComponent implements OnInit {
myHTML;
constructor(private sanitizer: DomSanitizationService, private myService : MyHTTPService){
myService.getHTMLFromBackend().subscribe(
data => {
this.myHTML = this.sanitizer.bypassSecurityTrustHtml(data.content)
});
}
ngOnInit() {}
}
Then when you are trying to use it in the html (DOM) Just simply do
{{myHTML}}

Cant get values of inputs asp.net

My problem i always get null from my inputs or default value. Some how if i set value at page_load like Form_txt_Ad.Value="ExampleValue"; i can get it. But i cant get any value from inputs.
protected void Save_Button_Click(object sender, EventArgs e)
{
string exapmle = Form_txt_Ad.Value;
string example = Form_txt_Soyad.Value;4
}
<div class="input">
<input type="text" translate translate-attr-placeholder=".PLACEHOLDER_NAME" placeholder="Ad" id="Form_txt_Ad" runat="server" />
<span><i class="glyphicon glyphicon-user"></i></span>
</div>
<div class="col-md-12" style="text-align: center;">
<button type="button" runat="server" onserverclick="Save_Button_Click" class="btn btn-success btn-raised btn-lg" title="Kaydet"><i class="glyphicon glyphicon-floppy-saved icon-marginRight"></i>Kaydet</button>
</div>
Thx for help.
Make sure all your control elements are placed inside <form> ... </form> tag.
Since you have placed runat="server" you should be able to get the value by either using any of them
Form_txt_Ad.Value
(OR)
Form_txt_Ad.Text
Else use Request.Form["Form_txt_Ad"]
Not sure though why not use a server side control using <asp:TextBox ... which will allow you to get the textbox value directly using the Text property
Add the name attribute to your input and make sure it's inside a form element.
<form>
...
<input type="text" translate translate-attr-placeholder=".PLACEHOLDER_NAME" placeholder="Ad" id="Form_txt_Ad" name="Form_txt_Ad" runat="server" />
...
</form>

Dynamic Text in Bootstrap Alert

I have a bootstrap alert like so :
<div class="alert alert-danger">
×
First Error
</div>
My problem is I want to be able to change this text dynamically in my code behind, c#. Ideally, I would like to have multiple bullet pointed error messages in one alert like the image below:
Can anyone provide me with any ideas of how to achieve this?
In your html, have this
<div id="BootstrapErrorMessage" runat="server">
</div>
and in your code, do this
....
MyErrorString += "<li>Bad Password</li>";
....
MyErrorString += "<li>Invalid Date</li>";
....
if (!MyErrorString.isNullOrEmpty()) {
BootstrapErrorMessage.InnerHtml += "×" +
"<ul>" + MyErrorString + "</ul>";
BootstrapErrorMessage.Attributes["class"] = "alert alert-danger";
}
You can download the error messages to the client when he request the model of your page(recommended solution). Or you can post your data to the server and get list of errors to show.
Your html code should be like this:
<div class="bs-example">
<div class="alert alert-danger fade in">
<ul>
<li><strong>First</strong> Error </li>
<li>Second Error</li>
</ul>
</div>
</div>
And each li element should be updated from server(One of the options you choose).

Categories

Resources