getting different paths using HttpPostedFileBase - asp.net

See the following code. I'm uploading files, Yet i'm getting different results from difference browsers.
Firefox var path = "about.restaurant.jpg"
yet in ie6 path = "D:\dev\xxxxx\xxxxx\xxxxx\Website\images\about.restaurant.jpg"
foreach (string file in Request.Files)
{
var hpf = Request.Files[file] as HttpPostedFileBase;
var path = hpf.FileName;
}
I had this issue in MVC2 . Just upgraded to MVC3. Same issue exist.
<form action="/Product/SaveUploadImage" method="post" enctype="multipart/form-data">
<input type="file" name="file" id="file" />
<input type="submit" value="Save" class="button" />
</form>

ah ok i see. so there is method that resolves all this
Path.GetFileName(hpf.FileName)

Related

the form Http POST doesn't work, only Get work in asp core mvc

I have a Form that should pass data through POST request, but GET request is being used without passing the data and do model binding of asp core, so buz of that the method Registrationp is never reach if the attribute [HttpPost] is in place ;( .
I tried many ways to get over this problem but none if them worked, even though the other forms post the data and bind the model successfully
HTML:
#model Student_Training.Models.File;
<form method="post" asp-controller="Students" asp-action="Registrationp" enctype="multipart/form-data">
<label asp-for="FileRep" class="col-sm-2 col-form-label"></label>
<div class="col-sm-10">
<div class="custom-file">
<input type="file" asp-for="FileRep" name="img" accept="image/*" class="form-control custom-file-input" />
<label class="custom-file-label"> Upload...</label>
</div>
</div>
<div class="form-group">
<button id="Button" type="submit" name="submit" formmethod="post" class="btn btn-secondary btn-sm">
<a asp-action="Registrationp"> Save </a>
</button>
</div>
</form>
Controller POST method:
[HttpPost]
public async Task<IActionResult> Registrationp([Bind("FileId, FileName, OwnerId, FileRep")] Student_Training.Models.File imgFileModel, IFormFile img, int? id)
{
var user = await _userManager.FindByNameAsync(User.Identity.Name);
var userEmail = user.Email;
Student Student = _context.Student.FirstOrDefaultAsync(x => x.Email == userEmail).Result;
// StudentId
id = Student.StudentId;
// Save img to wwwroot/img folder
string wwwRootPath = _hostEnvironment.WebRootPath;
Student_Training.Models.File myFile = new Student_Training.Models.File();
string fileName = Path.GetFileNameWithoutExtension(imgFileModel.FileRep.FileName);
string extention = Path.GetExtension(imgFileModel.FileRep.FileName);
imgFileModel.FileName = fileName = fileName + DateTime.Now.ToString("yymmss") + extention;
string path = Path.Combine(wwwRootPath + "/img/", fileName);
using (var fileStream = new FileStream(path, FileMode.Create))
{
await imgFileModel.FileRep.CopyToAsync(fileStream);
}
// insert recorod to Db
_context.Add(imgFileModel);
await _context.SaveChangesAsync();
return View();
}
As a matter of fact you are using an ancor tag to submit your form, not a submit button. An ancor tag is always generates a GET request. So just remove it from your code:
<button id="submitButton" type="submit" class="btn btn-secondary btn-sm">Save</button>

File upload not working using URLRequest in flex

I used upload functionality by html . using given code it's working fine .
<form id="avatar" enctype="multipart/form-data"
action="http://localhost:8080/alfresco/service/slingshot/profile/uploadavatar?
alf_ticket=TICKET_7475e180e8d258c0341fc745a3a35274d0a06e50"
method="post">
<input type="text" name="username" value="ken"/>
Select a file:
<input type="file" name="filedata" />
<input type="submit" name="button" value="upload" / /form
Same functionality I have tried in flex :
var uploadURL:URLRequest = new URLRequest();
uploadURL.url="http://localhost:8080/alfresco/service/slingshot/profile/uploadavatar?alf_ticket=TICKET_7475e180e8d258c0341fc745a3a35274d0a06e50"";
uploadURL.method=URLRequestMethod.POST;
uploadURL.contentType="multipart/form-data";
var params:URLVariables = new URLVariables();
params.username ="admin";
params.filedata=fileRef.data;
uploadURL.data = params;
fileRef.upload(uploadURL)
BUT GETTING Bad request error . so anybody know , what did i wrong in code . Please share with me .
In a POST request you are trying to send a parameter in URL..try sending alf_ticket as an attribute of params.

Play Framework How can i pass collection to action create()?

I am starter with Play Framework. I got a problem when i passed parameters.
I want to pass a collection from view to controller. And i do not know how to do this. I always get "null" when i get a collection from view.
My code below:
Code in controller:
public static void create(List<Book> books) throws Exception {
for(Book book : books){
System.out.println(book.get(0).author) // i got null :(
}
}
Code in HTML
Book 1:
<input type="text" name="books.author" />
<input type="text" name="books.title" />
Book 2:
<input type="text" name="books.author" />
<input type="text" name="books.title" />
When i submit, i want to add 2 records into database include Book1 and Book2. Please support me
Thanks
You can make this work by simplying add the array indicator to your HTML code
Book 1:
<input type="text" name="books[0].author" />
<input type="text" name="books[0].title" />
Book 2:
<input type="text" name="books[1].author" />
<input type="text" name="books[1].title" />
I have tested this solution, and it works fine.
Also note that your println will not compile, as you are calling get(0) on the Book object, and not the List object. If you just println book.author, it outputs the author as required.
In case anyone needs an example of the Javascript for dyanmically adding and removing books (JQUERY needed):
<script type="text/javascript">
$(document).ready(function() {
var bookCount=0;
$('#btnAddBook').click(function() {
bookCount++;
//newElem = go up a to the parent div then grab the previous container
var newElem = $(this).parent().prev().clone().attr('id', 'book[' + bookCount + ']');
//for each input inside the div, change the index to the latest bookCount
$(newElem).find("input").each(function(){
var name = $(this).attr('name');
var leftBracket = name.indexOf("[");
var rightBracket = name.indexOf("]");
var beforeBracketString = name.substring(0,leftBracket+1);//+1 to include the bracket
var afterBracketString = name.substring(rightBracket);
$(this).attr('name', beforeBracketString + bookCount + afterBracketString);
});
//insert it at the end of the books
$(this).parent().prev().after(newElem);
$(newElem).find("input").each(function(){
$(this).attr('id', $(this).attr('id') + bookCount);
});
//enable the remove button
$('#btnRemovebook').removeAttr('disabled');
//If we are at 16 divs, disable the add button
if (bookCount == 15)
$(this).attr('disabled','disabled');
});
$('#btnRemoveBook').click(function() {
bookCount--;
//remove the last book div
$(this).parent().prev().remove();
//in case add was disabled, enable it
$('#btnAddbook').removeAttr('disabled');
//never let them remove the last book div
if (bookCount == 0)
$(this).attr('disabled','disabled');
});
});
</script>
<!-- HTML Snippet -->
<div id="book[0]">
<label> Book: </label>
<input type="text" name="books[0].author" value="Author" />
<input type="text" name="books[0].title" value="Title" />
</div>
<div>
<input type="button" id="btnAddbook" value="Add another book" />
<input type="button" id="btnRemovebook" value="Remove last book" disabled="disabled" />
</div>
<!-- REST of the HTML -->

ASP.NET MVC IIS request.files doesn't work

Request.Files doesn't work when I deploy to the server but it works when I test locally. What do I need to configure to make this work when deployed?
Some example of your code would be nice, but this post helped me once:
A Back To Basics Case Study: Implementing HTTP File Upload with ASP.NET MVC including Tests and Mocks
This post from Phil Haack can be useful for you:
<form action="" method="post" enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="file" id="file" />
<input type="submit" />
</form>
[HttpPost]
public ActionResult Index(HttpPostedFileBase file) {
if (file.ContentLength > 0) {
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
file.SaveAs(path);
}
return RedirectToAction("Index");
}
Note that here you do not examine the Request.Files collection. Also example for the multiple file upload can be found there (main idea that you should use the IEnumerable<HttpPostedFileBase> in similar manner).

get the value sent by ajax

I have:
<form method="POST" name="f">
<input type="file" name="FileUpload" id="FileUpload" />
</form>
I'm sent the file using ajax,using the uplaod.file method:
document.getElementById('FileUpload').onchange = function() {
file = this.files[0];
ajax = new XMLHttpRequest;
ajax.file = file;
//etc..
ajax.open('post','Default.aspx', true);
ajax.setRequestHeader('foo','baa');
ajax.send(file);
}
Request.Forms["FileUplaod"] // don't works
How I get the value (the file) sent by ajax in my asp.net application?
I tried sent by http headers(is not pratice good,I know) but there problem with long length.
Thanks in advance.
try this form attribute :
form action="some/action" method="POST" enctype="multipart/form-data"

Resources