I am trying to upload a file i can able to upload a file but i need to post one parameter present in the form, now i need to post one parameter and upload file in the form.
I tried Multi part and Form url encoded in the consumes annotation. It is not working i am getting an error.
I used #FormDataParam and #FormParam annotation in the method.
java.lang.NullPointerException
org.glassfish.jersey.media.multipart.internal.FormDataParamValueFactoryProvider$FormDataParamValueFactory.provide(FormDataParamValueFactoryProvider.java:203)
org.glassfish.jersey.server.spi.internal.ParameterValueHelper.getParameterValues(ParameterValueHelper.java:81)
org.glassfish.jersey.server.internal.routing.SubResourceLocatorRouter.getResource(SubResourceLocatorRouter.java:220)
org.glassfish.jersey.server.internal.routing.SubResourceLocatorRouter.apply(SubResourceLocatorRouter.java:133)
org.glassfish.jersey.server.internal.routing.RoutingStage._apply(RoutingStage.java:128)
Server side:
#POST
#Path("import")
#Consumes(MediaType.MULTIPART_FORM_DATA)
#Produces(MediaType.APPLICATION_JSON + "; charset=UTF-8")
public void uploadScenario(#FormDataParam("importScenario") final InputStream is,
#FormDataParam("complectId") final Long complectId) {
// Realisation
}
Client side:
<form id="importForm" target="my_iframe" action="rest/exportimport/import" method="post" enctype="multipart/form-data">
<input id="uploader" type="file" name="importScenario" size="50"><input type="submit">
<input type="text" style="display:none" name="complectId" value="'+id+'">
</form>
Related
I've a requirement in reading two uploaded text/csv files separately using REST ws(Jersey), below a sample snippet that depicts the same.
#Path("bcmfileinput")
public class BCMFileInputCheckResource{
#POST
#Path("survivour1")
#Consumes(MediaType.MULTIPART_FORM_DATA)
#Produces(MediaType.TEXT_PLAIN)
public String getSurvivour1File(#FormDataParam(value="eaiTradesFile")InputStream eaiTradesStream,#FormDataParam(value="outsandingFile")InputStream outTradesStream) throws IOException{
//writing eaiTradesStream to the file to test
BufferedReader br = new BufferedReader(new InputStreamReader(eaiTradesStream,"UTF-8"));
PrintWriter f=new PrintWriter(new File("H:/abc.csv"));
String line="";
while((line=br.readLine())!=null ){
f.write(line);
f.println();
}
f.flush();
f.close();
return "H:/abc.csv";
}
And a sample html page:
<html>
<body>
<h2>BCM File Upload</h2>
<form action="http://localhost:9080/swiftmx/public/bcmfileinput/survivour1" method="post" enctype="multipart/form-data">
<p>
Select Eai Positions file : <input type="file" name="eaiTradesFile" size="45" />
<br>
<br>
Select Outstanding file : <input type="file" name="outsandingFile" size="45" />
</p>
<input type="submit" value="Upload It" />
</form>
</body>
</html>
With the above code, when i write any one of stream to the file then both the files data being printed.
But, my requirement is need to bind eaiTradesFile to 1st inputstream and outsandingFile file to 2nd inputstream as I've to process them separately for each file.
Been googling failed to find right solution for my requirement.
So, any solution is appreciable for the same, Thank all in advance!!!
I'm using Play! Framework 2.4. I can make a table and insert data via the evolution .sql scripts but how do I setup my Appication.scala, routes etc to make a form insert data?
PS I'm quite new to Play
The best way play fromework recommends is using helper and template system.
https://www.playframework.com/documentation/2.4.x/ScalaForms
But if you want to try with plain html and handler request in the controller by your own so you can try this:
Application.scala
def save = Action { implicit request =>
//here handle params from html form,
//this will return Option[Map[String,ArrayBuffer]]
val optionMap = request.body.asFormUrlEncoded
println(optionMap)
//saving things here
Ok("saved")
}
in plain html form
<form action="/savedata" method="post" accept-charset="UTF-8" enctype="application/x-www-form-urlencoded">
<input type="text" name="name" />
<input type="text" name="lastName" />
<input type="submit" />
</form>
conf/routes
POST /savedata controllers.Application.save
hope this helps.
regards
I'm working on my first web application. I am sending email with an url in it:
http://localhost:8080/HotelP/requeteSuccesO.jsp?hotelId=hampton&city=Montreal
When clicking on the link, requeteSuccesO.jsp displays the hotelId and city parameters:
out.println("<b>Hotel:</b> "+request.getParameter("hotelId")+"</br>");
out.println("<b>City:</b> "+request.getParameter("city")+"</br>");
Then the user can accept by clicking on a button:
<form method="get" action="acceptOffer">
<input type="submit" value="Accept" class="sanslabel">
acceptOffer is mapped to a servlet DecisionPage.java, and by clicking on that button it's calling the doGet() method.
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
System.out.println("in do get DecisionPage, hotelId is "+request.getParameter("hotelId"));
this.getServletContext().getRequestDispatcher( VUE_PAIEMENT ).forward( request, response );
}
The parameter hotelId received by the doGet function is null, but I am expecting it to be the value found in the url (in our case, "hampton")
Can anyone tell me why I get null and not "hampton" ?
When you make a form and submit that form to some action, it will only create request parameters for the fields you have defined in your form.
So, while you run the application with mentioned URL, it would contain those parameters and will be avilable to your jsp but if you don't include them in your form it won't be available to servlet when you submit the form.
So, you need to include those parameters to some hidden fields if you don't won't to show them to user.
Example:
<form method="get" action="acceptOffer">
<input type="hidden" name="hotelId" value="<%= request.getParameter(\"hotelId\")" %> /> <---- this field will create a new parameter with name as hotelId
<input type="hidden" name="city" value="<%= request.getParameter(\"city\") %>" />
<input type="submit" value="Accept" class="sanslabel">
</form>
So, now as we made a new fields hotelId and city they will be sent to your servlet acceptOffer and then you'll be able to access them with request parameter as below:
request.getParameter("hotelId")
You have to include those paramters in the form itself because the scope of the paramters is request scope. Something like this
<form method="get" action="acceptOffer">
<input type="text" name="hotelId" value=assign the value from request here/>
<input type="submit" value="Accept" class="sanslabel">
</form>
I'm trying to write a client that does all four REST verbs (GET/POST/PUT/DELETE) and have gotten all but the PUT done. The REST/CRUD API I'm working from wants to update an entry by calling PUT /realmen/ID-string and including the key-value pairs as JSON. For a POST this seems to work "automatically", but not for a PUT.
My HTML looks like:
<div id="list">
<form novalidate class="edit-form">
<p>Title <input ng-model="realmen.title" type="text" value="{{realmen.title}}" /></p>
<p>Real Men <input ng-model="realmen.realmen" type="text" value="{{realmen.realmen}}" /> </p>
<p>Real Role-Players <input ng-model="realmen.realroleplayers" type="text" value="realmen.realroleplayers}}" /></p>
<p>Loonies <input ng-model="realmen.loonies" type="text" value="{{realmen.loonies}}" /></p>
<p>Munchkins <input ng-model="realmen.munchkins" type="text" value="{{realmen.munchkins}}" /></p>
<input ng-model="realmen.entryId" type="hidden" value="{{entryId}}"/>
<button ng-click="change()">UPDATE ({{entryId}})"</button></p>
</form>
</div>
My controller looks like:
$scope.realmen = RealMen.get({entryId: $routeParams.entryId}, function() {
$scope.master = angular.copy($scope.realmen); // For resetting the form
});
$scope.change = function() {
console.log($scope.realmen);
RealMen.update({entryId: $scope.entryId}, function() {
$location.path('/');
});
}
And finally, my services look like:
angular.module('realmenServices', ['ngResource']).
factory('RealMen', function($resource){
var RealMen = $resource(
'http://localhost\\:3000/realmen/:entryId',
{},
{
query: {method:'GET', params:{entryId:''}, isArray:true},
post: {method:'POST'},
update: {method: 'PUT', params:{entryId:'#entryId'}},
remove: {method:'DELETE'}
});
return RealMen;
});
The PUT is getting called with the correct id value in the URL, but the Request Payload only contains the entryId, so the backend API gets no expected keys and values and essentially blanks out the record in the database.
The console.log($scope.realmen) does show the form fields, along with a lot of extra data. I tried calling RealMen.update($scope.realmen, ...) (similarly to calling .save()), but all those extra fields are tacked on as query string parameters to the URL in a spectacularly ugly fashion.
Because your $scope.realmen is a resource instance, instead of using RealMen.update, you can just call $scope.realmen.$update() (note that there is a "$"). The instance action method will take care of sending the data for you.
How should i write my controller class to upload an image through a form?
I have created the form like this
#{form #index(), enctype:'multipart/form-data'}
<br/>
<h4>Image:</h4> <input type="file" name="image" />
<br/>
<br/>
<input type="submit" name="submit" value="Upload Photo" />
#{/form}
There is agoo introduction here : http://www.lunatech-research.fr/playframework-file-upload-blob
If you upload multiple photos, there is some known problems. Here is a workaround that works for me : Multiple file upload in playframework
The enctype="multipart/form-data" is required to have Play framework handle all the upload.
On the controller side you just have to write :
public static void storeImage(File fileUpload) {
if (fileUpload == null) {
//Handle the error case
}
//Store the file in a perenial location.
//For example :
File storeLocation = new File("/relOrAbsPath"), fileUpload.getName());
boolean success = fileUpload.renameTo(storeLocation);
//...
}
By default Play stores the files in a temporary place.
You can also use annotations as you would do for other controller params.