Using FormData in servlet - java

I am having formData that contains a file
Like :
var files = document.getElementById("uploadfile").files;
/* Create a FormData instance */
var formData = new FormData();
/* Add the file */
var file = files[0];
alert(file.name);
formData.append('uploadfile', file, file.name);
client.open("POST", "fileupload?q="+uploadfile,true);
client.setRequestHeader("Content-Type", "multipart/form-data");
client.send(formData); /* Send to server */
Now i want to use this form data in my servlet fileupload.How to use it their ?Please help.

I am giving an example how I handled it in my project. I used doPost function to get it.
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
Do whatever you want with that item.
}

Related

how to get new request object after ajax called

I am developing WEB PROJECT using JSP and SERVLET.
I am trying to upload file using AJAX called.
File is successfully uploaded.
but, while ajax called controller (servlet file) send request and response object to jsp file.
JSP file
$(document).ready(function(){
$(':file').change(function(){
var fileObj = this.files[0];
var form = $('#mOBJ');
var fd = new FormData();
fd.append( 'file', fileObj);
$.ajax({
url:form.attr('action'),
type:form.attr('method'),
data:fd,
processData: false,
contentType: false,
async:false,
}).done(function(){
alert('ajax complete');
////////////////////////////////////////////////////////////////
Here i am getting old request value.
I want new request and response object after ajax called.
var Check2Bool = <%=context.getAttribute("comeFromUploadTemp")%>;
var check2 = <%=request.getAttribute("comeFromUploadTemp")%>;
alert(Check2Bool + " " + check2);
}).fail(function() {
alert( "error" );
$('#ldiv').hide();
});
});
Servlet
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
ServletContext context = getServletContext();
/**
* Display XML file to the user
*/
TemplateVO template = null;
TemplateUtil util = new TemplateUtil();
//Prepare XML file path
String path=(String) context.getAttribute(Constants.USER_DIR);
String strFilePath = null;
//Upload XML file
if(ServletFileUpload.isMultipartContent(request)){
try{
List<FileItem> multiparts = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
for(FileItem item : multiparts){
if(!item.isFormField()){
String name = new File(item.getName()).getName();
request.setAttribute("FileName",name);
String path1 = path + File.separator + "data-in";
strFilePath = FileUtil.createFileOnFileSystem(item,path1,name,"xml");
}
}
}catch(Exception ex){
ex.printStackTrace();
}
}
//set variables into Request Object
template = util.readXML(strFilePath);
context.setAttribute("comeFromUploadTemp", true);
request.setAttribute("comeFromUploadTemp", true);
request.getRequestDispatcher("mappingObject.jsp").forward(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
the request is JSP workspace, notajax.
u should pass data through response i.o. request.
like:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//... your code here
response.getOutputStream().write(data);
}
then u can parse response and get data as you want.
http://www.coderanch.com/t/522069/Servlets/java/Adding-Custom-Data-Response-Headers
http://www.w3schools.com/ajax/ajax_xmlhttprequest_response.asp

Fetching JSON object from Servlet Java

I want to create an application that will fetch a JSON object from a servlet to deserialize it, and then use its variables to do other things.
My servlet has the following code in the doPost:
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
ObjectOutputStream os;
os = new ObjectOutputStream(response.getOutputStream());
String s = new String("A String");
Gson gson = new Gson();
String gsonObject= gson.toJson(s);
os.writeObject(gsonObject);
os.close();
}
Now, while the servlet is running, I can access it via a browser, if I post same code in the doGet method, that would download a servlet file, which is not what I want.
What should I use in my second application that would connect to the servlet, fetch the object, so that I can manipulate it later?
Thanks in advance.
You need few changes in your servlet :
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String s = new String("A String");
String json = new Gson().toJson(s);
this.response.setContentType("application/json");
this.response.setCharacterEncoding("UTF-8");
Writer writer = null;
try {
writer = this.response.getWriter();
writer.write(json);
} finally {
try {
writer.close();
}
catch (IOException ex) {
}
}
}
If its downloading the servlet file instead of showing it in the browser , most probably you have not set the content type in the response. If you are writing a JSON string as the servlet response , you have to use
response.setContentType("text/html");
response.getWriter().write(json);
Please note the order , its "text/html" and not "html/text"
IfI understood the question correctly then you can use, java.net.HttpURLConnection and java.net.URL objects to create a connection to this servlet and read the JSON streamed by the above JSON servlet in your second servlet.

processing multipart/form-data

I'm doing file upload using XMLHttpRequest() in my jsp and when I do request.getContentType() in my controller I'm getting:
multipart/form-data; boundary=---------------------------4664151417711.
Further I'm not getting how to get the file and get the contents of it in my controller. Please anyone help.
Update --
I'm doing this in my jsp.
function fileUpload() {
var url= document.getElementById("urlId").value;
var file= document.getElementById("xslId").files[0];
var formdata = new FormData();
formdata.append("url", url);
formdata.append("file", file);
var xhr = new XMLHttpRequest();
xhr.open("POST","http://localhost:8080/XlsUpload/openSource.htm", true);
xhr.send(formdata);
xhr.onload = function(e) {
};
}
and in my controller--
public void openSource(#ModelAttribute("domTool") DomTool domTool,HttpServletRequest request,HttpServletResponse response){
String type=request.getContentType();
Further I'm struck how to get the contents of the uploaded file and the value of text field i.e.,URL in my controller. The type i'm getting as multipart/form-data
There is an Apache commons solution called commons-fileupload for parsing multipart content. You can find it here.
The most simple example copied from their tutorial looks like this:
#Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
List items = upload.parseRequest(request);
// iterate over items (i.e. list of FileItem) and access
// the content with getInputStream()
}

handle ajax request and send response java servlet

I have an ajax request function (written in JavaScript) and Java Servlet that handles this request. I need to get all request parameters and if it succeeded then send back a confirmation that it has succeeded. How I can send a confirmation message? As an attribute, like {isSuccess: true}. My code:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,
IOException {
Enumeration<?> paramNames = request.getParameterNames();
while (paramNames.hasMoreElements()) {
String paramName = (String) paramNames.nextElement();
// storing data fn
}
// how to send back a message here?
}
Get PrintWriter object by calling HttpServletResponse#getWriter and write your String.
response.getWriter().write("{isSuccess: true}");

Retrieve an Image from a POST request

I am trying to send a picture to my java servlet (hosted on amazon ec2) to later transfer it to amazon s3 and wonder how to retrieve the Image from the post request.
Upload Code
The request is sent through iOS RestKit API like this (pic.imageData is a NSData type):
RKParams* params = [RKParams params];
[params setValue:pic.dateTaken forParam:#"dateTaken"];
[params setValue:pic.dateUploaded forParam:#"dateUploaded"];
[params setData:pic.imageData MIMEType:#"image/jpeg" forParam:#"image"];
[RKClient sharedClient].username = deviceID;
[RKClient sharedClient].password = sessionKey;
[RKClient sharedClient].authenticationType = RKRequestAuthenticationTypeHTTPBasic;
uploadPictureRequest = [[RKClient sharedClient] post:kUploadPictureServlet params:params delegate:self];
Parsing Code Stub
This is how I parse the other 2 parameters on the Java servlet:
double dateTaken = Double.parseDouble(req.getParameter("dateTaken"));
double dateUploaded = Double.parseDouble(req.getParameter("dateUploaded"));
Question
The question is: how do I retrieve and parse the image on my server?
Servlet 3.0 has support for reading multipart data. MutlipartConfig support in Servlet 3.0 If a servelt is annotated using #MutlipartConfig annotation, the container is responsible for making the Multipart parts available through
HttpServletRequest.getParts()
HttpServletRequest.getPart("name");
References:
Servlet 3.0 File Upload handing files and params
Servlet 3.0 File upload Example
Something along the lines of this, using Apache Commons FileUpload:
// or #SuppressWarnings("unchecked")
#SuppressWarnings("rawtypes")
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
if (ServletFileUpload.isMultipartContent(request)) {
final FileItemFactory factory = new DiskFileItemFactory();
final ServletFileUpload upload = new ServletFileUpload(factory);
try {
final List items = upload.parseRequest(request);
for (Iterator itr = items.iterator(); itr.hasNext();) {
final FileItem item = (FileItem) itr.next();
if (!item.isFormField()) {
/*
* TODO: (for you)
* 1. Verify that file item is an image type.
* 2. And do whatever you want with it.
*/
}
}
} catch (FileUploadException e) {
e.printStackTrace();
}
}
}
Refer to the FileItem API reference doc to determine what to do next.

Categories