MVC 3 Update uploaded image with same name - asp.net-mvc-3

I'm stumped on an image issue... heres the lowdown.
In my layout i have an image that acts as a logo... however in the admin view there is the ability to upload a new logo and it simply replaces the current one with the exact same name. After the postback the image does not change on the layout to the updated image even though the updated image is saved. If I refresh the page with ctrl and F5, cache is gone and I can see the new image but I need it to be more automated.
Heres my img tag in the layout
<img src="#Url.Content("~/Content/themes/base/images/Client_Logo.jpg")" id="ClientLogo" alt="" width="227" height="130" style="float: left;" />
Heres the admin View
#using (Html.BeginForm("Admin", "Home", FormMethod.Post, new { #encType = "multipart/form-data" }))
{
<fieldset>
<legend>Logo Management</legend>
<p>
<input type="file" name="FileUpload" />
</p>
<p>
<input type="submit" value="Upload" />
</p>
</fieldset>
}
And finally the action
[Authorize]
[HttpPost]
public ActionResult Admin()
try
{
HttpPostedFileBase file = Request.Files[0];
if (file != null)
{
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/Content/themes/base/images"), fileName);
file.SaveAs(path);
System.IO.File.Delete(Path.Combine(Server.MapPath("~/Content/themes/base/images"), "Client_Logo.jpg"));
System.IO.File.Move(Path.Combine(Server.MapPath("~/Content/themes/base/images"), fileName), Path.Combine(Server.MapPath("~/Content/themes/base/images"), "Client_Logo.jpg"));
}
else
{
ModelState.AddModelError("uploadError", "There is a problem uploading the file.");
}
}
catch (Exception e)
{
ModelState.AddModelError("uploadError", e);
}
return View();
What does everyone suggest to do in order to refresh the image in the layout when the view is returned after uploading the image?
Cheers.

The quickest fix I can think of is displaying your logo with something random so the client would never hit the cache like:
"/images/yourlogo.png?version=123455634"
Replacing 123455634 with something always random.
Since the url of your picture will never be the same, the picture will always be downloaded.
You can mess with the cache headers for this particular file but this is the quickest fix I can think of.
Hope this helps.
EDIT try this:
<img src="#Url.Content("~/Content/themes/base/images/Client_Logo.jpg?version=" + DateTime.Now.Ticks.ToString())" id="ClientLogo" alt="" width="227" height="130" style="float: left;" />

Well, you could set caching headers on that file NOT to cache in your web.config but that isn't ideal.
How about some jQuery?
In your Layout:
<img src="#Url.Content("~/Content/themes/base/images/Client_Logo.jpg")" id="ClientLogo" alt="" width="227" height="130" style="float: left;" data-src="#Url.Content("~/Content/themes/base/images/Client_Logo.jpg")"/>
In your view that you want to change the image:
<script type="text/javascript">
$(function(){
$('#ClientLogo').attr('src',$('#ClientLogo').data('src') + '?t=' + new Date().getTime());
});
</script>

Related

Viewing an image captured in a Blazor Web Assembly PWA

Following on from the example Access Device Camera with Blazor I would like to view the image on the same page. So far I have found several older examples using JS but I think I should stick to native Blazor.
I think this is the start, but have failed to reference the file that was selected.
<p>
<h1>My Camera App</h1>
</p>
<input #onchange="updateCanvas" id="capturedPic" type="file" accept="image/*" capture>
<br />
<canvas id="picCanvas"> </canvas>
<br />
<br />
#code
{
public void updateCanvas()
{
//Code to place captured image in the canvas;
}
}
Following the .NET5 introduction of InputFile, I have the following solution.
The max size of an image is 500K so the code converts the camera photo to a 100x100 thumbnail.
Many thanks to Daniel https://devblogs.microsoft.com/aspnet/asp-net-core-updates-in-net-5-release-candidate-1/ and Naveen https://www.learmoreseekmore.com/2020/10/blazor-webassembly-fileupload.html
<div>
<InputFile OnChange="#OnFileSelection"></InputFile>
<div class="row">
<img src="#imgUrl">
</div>
</div>
#code{
string imgUrl = string.Empty;
private async Task OnFileSelection(InputFileChangeEventArgs e)
{
IBrowserFile imgFile = e.File;
string imageType = imgFile.ContentType;
var resizedImageFile = await imgFile.RequestImageFileAsync(imageType, 100, 100);
var buffers = new byte[resizedImageFile.Size];
await resizedImageFile.OpenReadStream().ReadAsync(buffers);
imgUrl = $"data:{imageType};base64,{Convert.ToBase64String(buffers)}";
}
}

Uploading photo Spring - Ajax

I am trying to upload a photo and get a preview of the uploaded image using Spring and Ajax.
I have the following code:
<h3>File Upload</h3>
<ul>
<li>
<form id="upload-form" method="post" enctype="multipart/form-data">
Select a file: <input type="file" name="uploadfile" size="45" accept="*" />
<br>
<input id="submit-button" type="submit" value="Upload" />
</form>
</li>
<li><p>Result: <br><span id="result"></span></p></li>
</ul>
<h3>Show Image</h3>
<ui>
<li>original:<img id="image-o" src="#" alt="original image" /></li>
<li>small: <img id="image-s" src="#" alt="small image" /></li>
<li>medium: <img id="image-m" src="#" alt="medium image" /></li>
<li>large: <img id="image-l" src="#" alt="large image" /></li>
<li>extra large: <img id="image-xl" src="#" alt="extra large image" /></li>
</ui>
<script type="text/javascript">
$(document).ready(function () {
$("#submit-button").on("click", function (event) {
event.preventDefault();
// create an FormData object
var data = new FormData($('#upload-form')[0]);
// disabled the submit button
$("#submit-button").prop("disabled", true);
// post data
$.ajax({
type: "POST",
enctype: 'multipart/form-data',
url: "image/api/upload",
data: data,
processData: false,
contentType: false,
cache: false,
timeout: 600000,
success: function (data) {
// shows server's response
// $("#result").text(data);
console.log("SUCCESS: ", data);
enableSubmitButton();
updateImages(data);
},
error: function (e) {
// shows server's response
// $("#result").text(e.responseText);
console.log("ERROR: ", e);
enableSubmitButton();
updateImages(e.responseText);
}
});
});
});
function enableSubmitButton() {
$("#submit-button").prop("disabled", false);
}
function updateImages(data) {
var url = 'http://localhost:9001/image/api/' + data;
$('#image-s').attr('src',url + '?size=s');
$('#image-m').attr('src',url + '?size=m');
$('#image-l').attr('src',url + '?size=l');
$('#image-xl').attr('src',url + '?size=xl');
$('#image-o').attr('src',url + '?size=o');
}
</script>
And my Java code:
#POST
#Path("/upload")
#Consumes(ExtendedMediaType.MULTIPART_FORM_DATA)
#Produces(ExtendedMediaType.APPLICATION_JSON_UTF8)
#Transactional
public ResponseEntity<Void> uploadImage(#RequestParam("uploadfile") MultipartFile file) {
if (file.getSize() < maxFileSize && validExtensions.contains(file.getContentType())) {
Image image = Image.builder().id(file.getSize()).build();
imageServiceConfigMapper.saveImage(image);
/* FormDataContentDisposition fileDetail = null;
ImageMetadata imageMetadata = buildImageMetadata(fileDetail, image);
imageServiceConfigMapper.saveMetadata(imageMetadata);*/
}
return new ResponseEntity<>(HttpStatus.OK);
When I choose a photo from my PC, it is accepted - see screenshot below:
When I click in upload, my browser gives the following answer:
The JSON looks like this:
BUT the selected picture is not showing:
Am I using a wrong URL?
The address of the site where I got the above screen ends is the one with index.html at the end, but I defined /api/upload as a relative path...
If I open the relative path, I got the following:
Or is it something wrong with the code responsible for the preview?
Sorry, I know there is a tones of similar issues but I could not found anything that hepled. I am quite a beginner...
Sorry for the long post and thanks for the help in advance!
Spring Content can do this and has a getting started guide and git repo with an angularjs based front-end that demonstrates exactly what you are trying to do. The getting started guide is here.

Input Button as Input image will not work

On my website i have a button which when clicked takes you to one of two random youtube videos. However i would like to change this to a image in stead of a button.I have tried to change it to a INPUT type="image" but this doesn't work. Here is the code i am using.
<SCRIPT language="JavaScript">
<!--
function get_random()
{
var ranNum= Math.floor(Math.random()*2);
return ranNum;
}
function getaGame()
{
var whichGame=get_random();
var game=new Array(2)
game[0]= "https://www.youtube.com/watch?feature=player_detailpage&v=NcFQF3PZFRk#t=722s";
game[1]= "https://www.youtube.com/watch?v=klBAW4MQffU";
location.href = game[whichGame];
}
//-->
</SCRIPT>
<FORM name="form1">
<center>
<INPUT type="button" onClick="getaGame()" >
</center>
</FORM>
Thanks for any help
An onclick event can be fired from any element. Here are some examples!

working with multiple and single file upload

I'm using uploadify fileupload plugin for my MVC3 project.
I'm trying to use the uploading file to the controller.
How do i use multi file upload and single file upload together ?
I know to use IEnumerable<HttpPostedFileBase> files for multiple files and HttpPostedFileBase files for single file upload. How to combine these.
In my project, the user may select multiple files or only a single file to upload it to the controller.
so, if i use IEnumerable<HttpPostedFileBase> files in my controller action, i'm unable to get single files(files is null) and if i use HttpPostedFileBase files it doesnot show anything, files is always null here.
How to get work with single file upload, i can get the multiple file uploads but not the single files.
How to get this work ?
Here is my code:
HTML
<body>
#using (Html.BeginForm("Index", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<div id="fileupload" style="display:none">
<div style="clear: none;">
File to Upload:
<input type="file" name="file_upload" id="file_upload" style="padding-left: 50px;"/><hr />
</div>
<p style="text-align: right;">
<input type="submit" id="selectimage" value="Ok" class="ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only"/>
<input type="submit" id="cancelimage" value="Cancel" class="ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only" onclick="cancelupload();" />
</p>
</div>
<input type="button" id="btnImg" />
<div id="filecontent">
Added Images:
</div>
}
</body>
<script>
$(function(){
$('#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) {
$("#selectimage").click(function () {
$("#file_upload-queue").appendTo("#filecontent");
});
}
});
});
</script>
Controller Action
public ActionResult Index(IEnumerable<HttpPostedFileBase> fileData)
{
foreach (var file in fileData)
{
if (file.ContentLength > 0)
{
string currpath = Server.MapPath("~/Images/");
currpath = Path.Combine(Server.MapPath("~/Images/Admin"), file.FileName);
file.SaveAs(currpath);
}
}
return View();
}
What should i change in controller action to get single file upload and multi file upload to work?
Update
Neither IEnumerable<HttpPostedFileBase> fileData nor HttpPostedFileBase fileData working
The controller action will be called multiple times for each file to be uploaded. But you seem to have hidden the upload form (you placed it in a div with display:none). Also you never use Uploadify to actually upload the files. You have set auto: false and you never trigger the file upload using the upload method. So I guess that you are somehow submitting the form and expecting to get something on the server side, but that's not gonna happen like this.
So, let's clean and simplify things up:
<div>
<input type="file" name="file_upload" id="file_upload" />
</div>
<hr />
<div id="filecontent">
Added Images:
</div>
<input type="button" id="upload" value="Upload selected files to the server" />
<script type="text/javascript" src="#Url.Content("~/Content/Uploadify/jquery.uploadify-3.1.min.js")"></script>
<script type="text/javascript">
$('#file_upload').uploadify({
'swf': '#Url.Content("~/Content/uploadify/uploadify.swf")',
'uploader': '#Url.Action("index", "home")',
'auto': false,
'multu': true,
'buttonText': 'Browse',
'fileTypeExts': '*.jpg;*.jpeg;*.png;*.gif;*.zip',
'removeCompleted': false,
'onSelect': function (file) {
$("#selectimage").click(function () {
$("#file_upload-queue").appendTo("#filecontent");
});
}
});
$('#upload').click(function () {
$('#file_upload').uploadify('upload', '*');
return false;
});
</script>
and your controller action could now become:
[HttpPost]
public ActionResult Index(HttpPostedFileBase fileData)
{
if (fileData != null && file.ContentLength > 0)
{
var currpath = Path.Combine(
Server.MapPath("~/Images/Admin"),
fileData.FileName
);
fileData.SaveAs(currpath);
}
return Json(new { success = true });
}
try it plugin: works with html5 + flash + silverligth according: client browser.
http://des.delestesoft.com:8080/?go=2

Uploading files with MVC 3 ajax style

Maybe it's just me but I'm trying to use a jQuery dialog to capture a file the user wants to upload. It must be supported by IE9. IE9 doesn't support the FormData object which is used in many examples and 3rd party tools I have came across. So in order to make my request not refresh the whole page I have to put my upload into an iFrame? Really? I know I can get some flash uploader but flash isn't supported on our site so that's out of the question right now.
Please.. please someone tell me I'm doing this wrong and there's an easier way because I can't seem to find it.. not one that will work on IE9 at least.
Form
<form action="/ControllerName/ActionName" method="post" enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="file" id="file" />
<input type="submit" name="submit" value="Submit" />
</form>
Then into an iFrame like this
<iframe src="myUrl"></iframe>
View:
#using (Html.BeginForm("FileUpload","Message",FormMethod.Post,new { enctype="multipart/form-data"})) {
#Html.ValidationSummary(true)
<fieldset>
<legend>Message</legend>
//your html here
<input type="file" name="files"/>
</fieldset>
Controller:
[HttpPost]
public ActionResult FileUpload(FormCollection values, IEnumerable<HttpPostedFileBase> files)
{
//do what you want with form values then for files
foreach (var file in files)
{
if (file.ContentLength > 0)
{
byte[] fileData = new byte[file.ContentLength];
file.InputStream.Read(fileData, 0, file.ContentLength);
//do what you want with fileData
}
}
}
I provide multiple files upload so i use
IEnumerable<HttpPostedFileBase> files
if you want only a single file then use only
HttpPostedFileBase file
and in your view change input type to
<input type="file" name="file"/>
Simple as that.
Regards
EDITED:
Take a look at more good examples:
http://www.strathweb.com/2012/04/html5-drag-and-drop-asynchronous-multi-file-upload-with-asp-net-webapi/
http://css.dzone.com/articles/implementing-html5-drag-drop
Regards

Resources