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()
}
Related
I want to show pdf in new tab after generated it, im using JQuery 1.12.3 and Spring MVC 4.
When i clic to my link, i generate pdf and my ajax method show success but my pdf isnt showed in new tab, what i've forgot ?
i've follewed this posts :
Display PDF in a webpage
Open ResponseEntity PDF in new browser tab
Spring - display PDF-file in browser instead of downloading
I've tried to remove ResponseBody annotation, but i've the same result
Here is my code :
HTML :
<a id="3676274" class="bulletinLink" target="_blank" href="#">Bulletin du 2015-04-30</a>
JQuery :
$(".bulletinLink").click(function(e){
e.preventDefault();
var id = $(this).attr('id');
var oAjax;
var sUrl = sUrlBase + '/generatePdf/'+id;
oAjax = $.ajax({
url: sUrl,
type: 'GET',
cache: false,
data : '',
async : false
});
oAjax.done(function(transport) {
alert("success");
});
oAjax.fail(function(transport) {
alert("fail");
});
});
Java :
#RequestMapping(value = "/generatePdf/{id}", method = RequestMethod.GET)
#ResponseBody
public final ResponseEntity<byte[]> generateWithResponseBody(#PathVariable("id") final int idBulletin
,final HttpServletRequest httpRequete, final HttpServletResponse httpReponse) throws ApplicationException
{
...
HttpHeaders headers = new HttpHeaders();
headers.setContentType( MediaType.parseMediaType( "application/pdf" ) );
String filename = "spring_tutorial.pdf";
headers.setContentDispositionFormData( filename, filename );
headers.setCacheControl("must-revalidate, post-check=0, pre-check=0");
ResponseEntity<byte[]> response = new ResponseEntity<byte[]>(out.toByteArray(), headers, HttpStatus.OK);
return response;
}
The problem is you need to add the file to the HttpServletResponse, and no need to return any value in your method, so use void, adding the file to the response, the browser will handle it correctly
#RequestMapping(value = "/generatePdf/{id}", method = RequestMethod.GET)
#ResponseBody
public final void generateWithResponseBody(#PathVariable("id") final int idBulletin
,final HttpServletRequest httpRequete, final HttpServletResponse reponse) throws ApplicationException
{
//Here retrieve your PDF file
if(file != null) {
String mimeType = URLConnection.guessContentTypeFromName(file.getName());
if (mimeType == null) {
logger.debug("mimetype is not detectable, will take default");
mimeType = "application/pdf";
}
logger.debug("mimetype : {}", mimeType);
response.setContentType(mimeType);
response.setHeader("Content-Disposition", String.format("attachment; filename=\"%s\"", file.getName()));
response.setContentLength((int) file.length());
InputStream inputStream = new BufferedInputStream(new FileInputStream(file));
FileCopyUtils.copy(inputStream, response.getOutputStream());
}
}
I've change my jquery function without Ajax like this and it works know :
window.open(sUrl);
Also, for displaying my pdf in the tab and dont download it, i remove this instruction in controller :
headers.setContentDispositionFormData( filename, filename );
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
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.
}
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.
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.