Error uploading file from form-data to Spring Server - spring-mvc

I am uploading a picture using form-data taking the picture from the Client's PC to Spring MVC Server.
Update Page:
<!DOCTYPE html >
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Spring MVC - Upload File</title>
</head>
<body>
<form id="form1" method="post" action="/upload" enctype="multipart/form-data" accept-charset="utf-8">
<!-- File input -->
<input name="file" id="file" type="file" /><br/>
<input type="submit" value="Upload" />
</form>
</body>
</html>
And this is the Spring Controller
#RequestMapping(value = "upload", method = RequestMethod.POST)
public #ResponseBody
String provaUpdate(MultipartHttpServletRequest request,Principal p,HttpServletResponse response)throws IOException {
String result="";
LocalFileManager mLocalFileManager = LocalFileManager.get();
Iterator<String> iterator = request.getFileNames();
while(iterator.hasNext())
{
System.out.println("iterator.next()="+iterator.next());
}
System.out.println("request.getFileMap().isEmpty()??"+request.getFileMap().isEmpty());
// mLocalFileManager.saveLocalData(g,g.getPicturesCount(), request.getFile("new").getInputStream());
return result;
}
So, when i run that, it just prints:
request.getFileMap().isEmpty()??true
Then, no Files seems to be uploaded, but if I get the request.getInputStream() I can write a TXT File showing that:
------WebKitFormBoundaryWG8vA5PuTFFxPBqK
Content-Disposition: form-data; name="file"; filename="1.jpg"
Content-Type: image/jpeg
�� JFIF ��ICC_PROFILE 蠠 mntrRGB XYZ ٠ $ acsp �� ӭ )𽞯򕮸B򤊃9
desc D ybXYZ bTRC Ԡ dmdd ࠠ ɧXYZ
h gTRC Ԡ lumi
| meas
//(Symbols) Long ETC, so the picture is sent !!
------WebKitFormBoundaryWG8vA5PuTFFxPBqK--
So, seems that the picture is sent correctly but the MultipartHttpServletRequest is not able to get the File.
Which is my mistake?

I think,you may be missing below entry in your spring configuration xml file.
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- below properties can be configured as per your need -->
<property name="maxUploadSize" value="5000000" />
<property name="maxInMemorySize" value="5000000" />
</bean>

The mistake was that i am working with Thymeleaf, so the form is different.
It is solved changing that:
1- Create a class that contains a MultipartFile, like this:
public class Images {
MultipartFile image;
public MultipartFile getImage() {
return image;
}
public void setImage(MultipartFile image) {
this.image = image;
}
}
2- The correct form code for a Spring Server working with Thymeleaf:
<form id="myform" action="#" th:action="#{/upload}" th:object="${Images}" method="POST" modelAttribute="Images" enctype="multipart/form-data">
<input type="file" th:field="${Images.image}" name="file"/>
<input type="submit" value="Upload"/>
</form>
And finally the correct Controller method:
#RequestMapping(value = "upload", method = RequestMethod.POST)
public String addVocabularyValadate( #ModelAttribute("Images") Images images,BindingResult bindingResult,
Model model) throws IOException
{
System.out.println("inputstream Nombre!"+images.getImage().getOriginalFilename());
if(bindingResult.hasFieldErrors() == true)
return "error";
else
return "upload OK!";
}

Related

MultipartFile always null Spring MVC return Response 400 for Upload Excel

I have a problem when uploading using multipartfile. Always return response 400. Required request part files is not present. I have tried many ways. but none worked
i have tried to register CommonsMultipartResolver. but still didnt work for me.
#RequestMapping(value = "/viewFormReportUpload.html",method = RequestMethod.POST)
public ModelAndView uploadFormPage(#ModelAttribute("viewForm") ViewFormDownload viewForm,
#RequestParam("file") MultipartFile files, BindingResult result) throws IOException {
//some code
}
<form:input path="files" type="file" id="file" name="files" accept=".xls,.xlsx" class="form-control" />
try this
<form:input path="files" type="file" id="file" name="file" accept=".xls,.xlsx" class="form-control" />

Required CommonMultipartFile parameter 'testFile' is not present in spring mvc

when I upload a file to springmvc, getting a error message "Required CommonsMultipartFile parameter 'textFile' is not present", I don't know why I can meet it, that's my code.
<form id="form" enctype="multipart/form-data">
<input type="text" id="username" name="username" />
<input type="file" id="file" name="textFile" />
<input type="button" onclick="test()" value="上传" />
</form>
<script type="text/javascript">
function test(){
var form = new FormData(document.getElementById("form"));
$.ajax({
url:"http://localhost:8080/giraffe/upload1",
type:"post",
data:form,
cache: false,
processData: false,
contentType: false,
success:function(data){
alert("success!");
}
});
}
That's my controller and configuration.
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="UTF-8"/>
<property name="maxUploadSize" value="10240000"/>
</bean>
#RequestMapping(path = "/upload1", method = RequestMethod.POST)
public Object updloadImage(#RequestParam("textFile") CommonsMultipartFile file){
String fileName = file.getOriginalFilename();
return null;
}
Maybe you should change your RequestParam to
#RequestParam MultipartFile textFile
This is of type "org.springframework.web.multipart.MultipartFile"
Also important is that you expose the commons library to your server. So you must add your commons-fileupload-x.x.x.jar to the WEB-INF/lib folder.
And your controller must add the path
#RequestMapping(value="/giraffe")
because your AJAX-Request points to /giraffe/upload1
To check what and if anything is presented to the controller you can add
#RequestParam (required=false) ...
If you have an jsp-File for the page and no plain html then you can use the jstl. This can help you avoid problems with the correct url in your AJAX-request. Like this
url: "<c:url value='/giraffe/upload1' />",

How to Send Post request in java with javax.portlet.ActionResponse.sendRedirect method?

I want to POST to URL but following making it as GET , so How can I POST the
Object portletResponse = webAppAccess.getHttpServletRequest()
.getAttribute(Constants.PORTLET_RESPONSE);
if (portletResponse instanceof javax.portlet.ActionResponse) {
javax.portlet.ActionResponse actionResponse = (javax.portlet.ActionResponse) portletResponse;
actionResponse.sendRedirect(URL);
}
Have you tried to use RequestDispater instead of response.sendRedirect?
It retains the original request, without changing it.
So, it will remain POST if it was POST.
I have done this by using FORM POST method as follows.
webAppAccess.processPage("importedPage");
Added this imported Page in model :
<HTML>
<HEAD>
<title>New Page</title>
</HEAD>
<Body onload="">
<form id="FormID" method="POST" action="actionURL">
<input type="hidden" name="id" id="ID" value="<%=webAppAccess.getVariables().getString("ID")%>"/>
<noscript>
<p>Your browser does not support JavaScript or it is disabled.
Please click the button below to process the request.
</p>
<input type="submit" value="Proceed " name ="submit"></input>
</noscript>
<script>
document.getElementById('FormID').submit();
</script>
</form>
and then MVC controller mapping as follows:
#RequestMapping(value = {"/Details"}, method = RequestMethod.POST)
public String mthDetails(final Model p_model, #RequestParam(value = "id", required = false) final String p_ID){
//code for further logic using ID
}

Avoid ajax file upload attack

I have a form and in a HTML form inside which I have file upload button.
File is going to be uploaded using AJAX request.
On file upload I am checking extension and file size.
I am uploading file into /home/xyz/upload/username/username_timestamp
But since I am using AJAX request, I cannot(and don't want to) use the CAPTCHA and there is a risk of attacker flooding with files. How can I deal with this issue?
PS: I am using Spring-MVC(not spring security) and Struts2 in my projects, so framework specific solution will be icing on a cake.
Protect your action to be called out of expected by using Strut's token mechanism and your expected logic of file uploads inside your parent action (e.g. max uploads per minutes) ; something like below:
index.jsp
<form action="upload" method="post" enctype="multipart/form-data">
<label for="myFile">Upload your file</label>
<input type="file" name="myFile" />
<s:if test="uploadsPerMinutes < 10">
<s:token name="tknUpload" /> <!-- *** conditional generate token *** -->
</s:if>
<sj:submit value="Submit Form" targets="myAjaxTarget"/>
</form>
<div id="myAjaxTarget">
</div>
struts.xml
<action name="upload" class="com.upload.FileUpload">
<interceptor-ref name="tokenSession/>
<interceptor-ref name="basicStack"/>
<result name="success" type="stream">...</result>
</action>
<action name="uploadParent" class="com.upload.FileUploadParent">
<result name="success">index.jsp</result>
</action>
FileUploadParent.java
public class FileUploadParent extends ActionSupport{
...
public static int uploadsPerMinutes = 0;
private static DateTime lastUploadTime;
public String execute()
{
...
synchronized(uploadsPerMinutes){
if(currentTime - lastUploadTime > 1min) uploadsPerMinutes=0;
else uploadsPerMinutes++;
lastUploadTime = currentTime;
}
return SUCCESS;
}
public String getUploadsPerMinutes()
{
return uploadsPerMinutes;
}
}
With these, client have to get a token from server for each file upload. These are behind the scene and do not disturb your normal users.

ASP.NET WEB API Not able to retrieve Post Parameters

I trying to retrieve post parameters in web API but I do get null values everytime.
My html
<form method="POST" action="http://localhost:16192/update" name="myform">
<input name="title" type="text"/>
<input name="isbn" type="text"/>
<input name="author" type="text"/>
<input type="submit" value="Submit"/>
</form>
And My WebAPI
[HttpPost]
[Route("UPDATE/")]
public String updateRecord([FromBody]String title,String isbn="", String author="")
{
return "Updated";
}
The updateRecord method is being called but I always get null values. Any help would be greatly appreciated.
[HttpPost]
[Route("UPDATE/")]
public String updateRecord([FromBody]dynamic values)
{
var title = values.title.Value;
....
return "Updated";
}
or you can create a DTO object (paragraph 2):
http://encosia.com/using-jquery-to-post-frombody-parameters-to-web-api/

Resources