how to get data from a form("multipart/form-data") with springMvc? - spring-mvc

how to get data from a form("multipart/form-data") with springMvc?
i want to upload a file(a photo),so the type of form is 'multipart/form-data'
but i found that springMVC cannot map data(in the form) into the property of User,I know i should use multipartFile to accept the picture,but how can other data in the form be mapped into object User automatically ?
<form enctype="multipart/form-data" type="post" action="....">
<input type"file" name="photo"/>
<input type"text" name="username"/>
.....
</form>
#RequestMapping("...")
public String editUser(User user,MultipartFile multipartFile){
.....
}
I get a 400 bad request error,so does anyone know how to achieve it? thanks a lot if someone help me out

You can do like this:-
<form enctype="multipart/form-data" type="post" action="....">
<input type"file" name="photo"/>
<input type"text" name="username"/>
.....
</form>
add model attribute on this page and use it in
your controller like this:-
#RequestMapping("...")
public String editUser(#RequestParam("photo") MultipartFile photo,
#ModelAttribute("your model attribute") User user){
.....
}

Related

Cannot upload an image

I'm trying to update an image to my database, I defined as property model (bounded by database) the following:
public byte[] AvatarImage { get; set; }
then I created another property which store the value in the ViewModel:
public IFormFile AvatarImage { get; set; }
this steps are also described here in the doc.
Iside my form, I added the following html:
<div class="form-group text-center col-lg-12">
<img src="#Model.AvatarImage" class="avatar img-circle" alt="avatar" />
<h6>#Localizer["UploadNewAvatar"] ...</h6>
<input type="file" class="form-control" id="avatarUrl" asp-for="#Model.AvatarImages" />
</div>
when I submit the form the property AvatarImage is even null. But I don't understand why happen this, because all the other form properties are valorized correctly
Sounds like you are missing the form enctype.
Make sure you have:
<form enctype="multipart/form-data">
... inputs
<form>
Your <input type="file"> element assignment below seems to be wrong, because it uses #Model directive which outputs value of AvatarImages property (and the property is not exist in viewmodel class):
<input type="file" class="form-control" id="avatarUrl" asp-for="#Model.AvatarImages" />
The correct way is just using the property name like example below, because asp-for="PropertyName" is equivalent to model => model.PropertyName in HTML helper (assumed you have #model directive set to a viewmodel class):
<input type="file" class="form-control" asp-for="AvatarImage" />
Also don't forget to specify enctype="multipart/form-data" attribute in <form> tag helper:
<form asp-controller="ControllerName" asp-action="ActionName" method="post" enctype="multipart/form-data">
<!-- form contents here -->
</form>
Reference: Tag Helpers in forms in ASP.NET Core
First add enctype="multipart/form-data" to form ;
Then,check your #model, two situations :
1.Use Model directly, since the image is a byte array type, you need to convert the file type to byte[] during the submission process.
2.Or you could use ViewModel, and change the parameter type to viewmodel in the method.

Value getting Null from Iformcollection in nop4.0 when submit the form

I want data from Iformcollection in nopCommerce 4.0 it getting null value.
This is my post method in controller
[HttpPost]
public ActionResult UpdateCart(int Id, IFormCollection form)
{
var setting = settingService.LoadSetting<DemoSetting>(_storeContext.CurrentStore.Id);
//Check plugin is enabled or not
if (!_setting.DemoSettingEnabled)
return Content("");
//Check null value
if Id,<= 0)
throw new ArgumentNullException("Id,");
This is my view page from which i can post data
<form asp-controller="DemoDiscounts" asp-action="UpdateCart" asp-antiforgery="true"
asp-route-Id="#Model.Id" asp-route-id="product-attributes-form" >
Can you please suggest if any one have solution?
Hey You can try this hope so it will helpful to you
<form method="post" asp-controller="YourControllerName" asp-action="YourActionName" asp-route-Id="#Model.Id" id="product-attributes-form" role="form">
Main thing you forgot Method="Post" and give id="product-attributes-form" role="form" hope so it can helpful to you
You need to add role parameter in tag
i.e. role="form"
<form method="post" role="form">
...
...
</form>

Spring MVC is confusing get and post methods with the same request mapping

I have a login controller that I've mapped the "/login" path to two different methods. One will be called for get and the other for post.
#RequestMapping(value = "/login", method = RequestMethod.GET)
public String login(Model model){
LoginDto loginDto = new LoginDto();
model.addAttribute("loginDto", loginDto);
return "home/login";
}
#RequestMapping(value = "/login", method = RequestMethod.POST)
public String doLogin(#Valid LoginDto loginDto, BindingResult bindingResult){
if(bindingResult.hasErrors()){
return "home/login";
}
return "redirect:/";
}
I have the thymeleaf form
<form method="POST" th:action="#{/login}" th:object="${loginDto}">
<div class="form-group-row">
<label> Email </label>
<input type = "text" th:field = "*{email}"/>
<span th:if="${#fields.hasErrors('email')}" th:errors = "*{email}"></span>
</div>
<div>
<label> Password </label>
<input type = "text" th:field = "*{password}"/>
</div>
<input type="submit" />
</form>
When enter data and click submit the method with the GET request is called. I know this from inserting breakpoints in both methods. Also the url now has a ?errors at the end of it. I've also changed the url mapping to the second method to "doLogin" like this
#RequestMapping(value = "/dologin", method = RequestMethod.POST)
public String doLogin(#Valid LoginDto loginDto, BindingResult bindingResult){
if(bindingResult.hasErrors()){
return "home/login";
}
return "redirect:/";
}
and changed the form to this
<form method="POST" th:action="#{/dologin}" th:object="${loginDto}">
<div class="form-group-row">
<label> Email </label>
<input type = "text" th:field = "*{email}"/>
<span th:if="${#fields.hasErrors('email')}" th:errors = "*{email}"></span>
</div>
<div>
<label> Password </label>
<input type = "text" th:field = "*{password}"/>
</div>
<input type="submit" />
</form>
and it works. I can enter data and hit the submit button and I'm in the doLogin method. However, I would like to keep this mapping of GET and POST to the same url to do different things based on the request method.
Further more, when I created the form at first, I forgot to specify a method="post" and while testing it submitted get requests to "/login" from this form. Perhaps that wired something up that needs to be unwired.
Is this a bug? I can map the same url with different request methods to other controller methods but this one doesn't seem to want to work. Any Ideas?
I've figured it out. The reason the method that is mapped to the POST request is because I'm using spring security and it's not completely set up. The login page for spring security was mapped to /login as well and the appended
localhost/login?error
to the url string is something spring security appends when there is an error with the login process. I have not set up authentication with spring security yet so it believes there's an error. I will continue on setting up spring security but this is the reason my POST request was not mapped to the doLogin method.

SPRING MVC post method call not working

By JSP has below :
<h2>Student Information</h2>
<form:form method="POST" action="/HelloWeb/addStudent">
<table>
and my java controller code has below
#RequestMapping(value = "/addStudent", method = RequestMethod.POST)
public String addStudent(#ModelAttribute("SpringWeb") Student student,
ModelMap model) {
when i try to hit the post doesnt work i,e /HelloWeb/addStudent,
I tried making both places /HelloWeb/addStudent or just /addStudent that doesnt work.
FYI : HelloWeb here is the DispatchServletName given in web,xml
I am trying example given in site
http://www.tutorialspoint.com/spring/spring_mvc_form_handling_example.htm
I apologize if i am asking very basic easisest issue, BUt tried this # late nite and fed up so requesting ppl to help/suggest
The attribute in jsp require modelAddribute or commandName which is the class instance of the domain object. You did not specify it. So the
<form:form method="POST" modelAttribute="SpringWeb" action="/HelloWeb/addStudent">.
There is a standard way to do form post submission in spring. You need to do GET request mapping to map/bind the Student table with jsp, and POST mapping to submit jsp form data. An example in your case would be.
#RequestMapping(value = "/addStudent", method = RequestMethod.GET)
public String addStudent(#ModelAttribute("SpringWeb") Student student) {
return "addstudentJsp"; // your jsp page name where the spring:form is placed
In jsp page do this
<h2>Student Information</h2>
<form:form modelAttribute="SpringWeb">
<form:input id="name" path="name" type="text" class="form-control" />
<form:errors path="name" cssClass="text-danger"></form:errors>
// your student fields
<button type="submit">submit</button>
</form:form>
Now again in your controller have a post request method like
#RequestMapping(value = "/addStudent", method = RequestMethod.POST)
public String addStudent(#ModelAttribute("SpringWeb") Student student, #BindingResult result) {
//Call to your data persistence layer like StudentService
}
The modelAttribute does the binding for you
I faced same problem, I just rename my project "HelloWeb" and the problem was solved.

How to redirect #Url.Action

I have link with parameter:
[http://localhost:8545/Admin/Agent/ManageUser?agentId=3230][1]
After change language new link:
[http://localhost:8545/Admin/Agent/ManageUser][2]
have error beacause haven't ?agentId=3230
i use :<input type="hidden" name="ReturnUrl" value="#Url.Action(null)" />
i don't know edit #Url.Action(null), please help me. thanks!
try this input
<input type="hidden" name="ReturnUrl" value="#Url.Action(ViewContext.RouteData.Values["controller"].ToString(), ViewContext.RouteData.Values["action"].ToString(), new { agentId = Request.QueryString["agentId"] })" />
Firs parameter if Url.Action is controller name, second parameter is action name and last one the routeValues can you add query strings in URL.
If you just need to return the user to the same URL he was before changing the language, just keep the full URL in your hidden input as follows:
<input type="hidden" name="ReturnUrl" value="#Request.Url.AbsoluteUri" />
Also (assuming your ChangeLanguage method is accessibly using the same host-name), you could simply do:
public ActionResult ChangeLanguage(string lang)
{
// something like...
// Session["Lang"] = lang;
return Redirect(Request.UrlReferrer.ToString());
}

Resources