valums fileuploader doesnt work under IE 9 using spring - ajax

i am working on file uploading using spring MVC,it work fine in firefox and chrome but in IE its show fail of uploading.. below is my jsp page where i include fileuploader function.
<div id="file-uploader-demo1" style="float: left;padding-top: 10px"></div>
</div>
<script>
function createUploader(){
var uploader = new qq.FileUploader ({
element: document.getElementById('file-uploader-demo1'),
action: '/Flas_ _/commu-____/insertFile;jsessionid=${sessionId}',
headers: {'Content-type':'multipart/form-data'},
multipleFileUpload: false,
debug: true
});
}
window.onload = createUploader;
</script>
here is my jsp page where iam including FileUploader.js file the action tag calls my respective controller which is shown below..
#RequestMapping(value = "/insertFile", method = RequestMethod.POST)
public String fileUpload(#RequestParam("qqfile") String filename1,ModelMap map,
HttpServletRequest request,HttpServletResponse response) throws IOException {
PrintWriter writer = null;
InputStream is = null;
FileOutputStream fos = null;
try {
writer = response.getWriter();
} catch (IOException ex) {
//log(OctetStreamReader.class.getName() + "has thrown an exception: " + ex.getMessage());
}
String filename = request.getHeader("X-File-Name");
this.setFILEUPLOAD(filename);
try {
is = request.getInputStream();
fos = new FileOutputStream(new File("F:/images/" + filename));
IOUtils.copy(is, fos);
response.setStatus(response.SC_OK);
writer.print("{success: true}");
} catch (FileNotFoundException ex) {
response.setStatus(response.SC_INTERNAL_SERVER_ERROR);
writer.print("{success: false}");
// log(OctetStreamReader.class.getName() + "has thrown an exception: " + ex.getMessage());
}catch (IOException ex) {
response.setStatus(response.SC_INTERNAL_SERVER_ERROR);
writer.print("{success: false}");
// log(OctetStreamReader.class.getName() + "has thrown an exception: " + ex.getMessage());
} finally {
try {
fos.close();
is.close();
} catch (IOException ignored) {
}
}
writer.flush();
writer.close();
return "do-nothing";
}
though in CHROME and FIREFOX its works fine and i get the file to store in locale drive. But it doesn't work in IE 9. what should i do i am not getting.
any solution for dis? plz help Thanks.

I solved the other problem (working in IE, not working in FF) by implementing two controller methods. I did not sent explizit headers with the JavaScript uploaders configuration.
One method (for IE) has additional RequestMapping-Options:
headers = { "content-type=multipart/form-data" }
The RequestParam for IE is a MultipartFile. From that you will get the filename and the content. The request body of the normal multipart upload used by IE does not only contain the file content as the ajax upload with Firefox does. It also has multipart informationn like the filename and boundaries. MultipartFile can handle this for you.
As far as I know, some general settings have to be done to enable your webapp dealing multipart file uploads. But that's another question.

Related

Spring mvc When using enctype="multipart/form-data" modelAttribute values equal null in the controller

I use spring mvc I want to uplaod image to jsp form so I add enctype="multipart/form-data" to the form tag but when i add this, modelAttribute values equals null in the controller
This is my form in jsp page:
<form:form action="saveContact" method="post" modelAttribute="Contacting" id="container" enctype="multipart/form-data">
This is the header of the function in controller:
#RequestMapping(value = "/saveContact", method = RequestMethod.POST)
public ModelAndView saveContact(#ModelAttribute ("Contacting") Contacting Contacting,ModelAndView modelndView,HttpServletRequest request ,HttpServletResponse response
) throws Exception {............}
#ModelAttribute ("Contacting") Contacting Contacting all values are null. and When I erease the enctype="multipart/form-data" from form tag its work well but I cant upload the image
this is the uplaud function:
public void uplaodImages(String url,HttpServletRequest request) {
// configures upload settings
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold(THRESHOLD_SIZE);
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setFileSizeMax(MAX_FILE_SIZE);
upload.setSizeMax(MAX_REQUEST_SIZE);
String uuidValue = "";
FileItem itemFile = null;
try {
// parses the request's content to extract file data
List formItems = upload.parseRequest(request);
Iterator iter = formItems.iterator();
// iterates over form's fields to get UUID Value
while (iter.hasNext()) {
FileItem item = (FileItem) iter.next();
if (item.isFormField()) {
if (item.getFieldName().equalsIgnoreCase(UUID_STRING)) {
uuidValue = item.getString();
}
}
// processes only fields that are not form fields
if (!item.isFormField()) {
itemFile = item;
}
}
if (itemFile != null) {
// get item inputstream to upload file into s3 aws
BasicAWSCredentials awsCredentials = new BasicAWSCredentials(AMAZON_ACCESS_KEY, AMAZON_SECRET_KEY);
AmazonS3 s3client = new AmazonS3Client(awsCredentials);
try {
ObjectMetadata om = new ObjectMetadata();
om.setContentLength(itemFile.getSize());
om.setContentType("image/png");
String ext = FilenameUtils.getExtension(itemFile.getName());
String keyName = uuidValue + '.' + ext;
// s3client.putObject(new PutObjectRequest(S3_BUCKET_NAME,"99/after/img", itemFile,st om));
// s3client.setObjectAcl(S3_BUCKET_NAME, "99/after/img", CannedAccessControlList.PublicRead);
TransferManager tm = new TransferManager(new ProfileCredentialsProvider());
System.out.println("Hello");
// TransferManager processes all transfers asynchronously,
// so this call will return immediately.
Upload upload1 = tm.upload(
S3_BUCKET_NAME, url, itemFile.getInputStream(),om);
System.out.println("Hello2");
try {
// Or you can block and wait for the upload to finish
upload1.waitForCompletion();
System.out.println("Upload complete.");
} catch (AmazonClientException amazonClientException) {
System.out.println("Unable to upload file, upload was aborted.");
amazonClientException.printStackTrace();
}
} catch (AmazonServiceException ase) {
// LOGGER.error(uuidValue + ":error:" + ase.getMessage());
} catch (AmazonClientException ace) {
//LOGGER.error(uuidValue + ":error:" + ace.getMessage());
}
} else {
//LOGGER.error(uuidValue + ":error:" + "No Upload file");
System.out.println("No Upload file");
}
} catch (Exception ex) {
//LOGGER.error(uuidValue + ":" + ":error: " + ex.getMessage());
System.out.println(ex.getMessage());
}
//LOGGER.info(uuidValue + ":Upload done");
System.out.println("Upload done");
}
#RequestMapping(value = "/form.html", method = RequestMethod.POST)
public String handleFormUpload(#RequestParam("name") String name,
#RequestParam("file") MultipartFile file) throws Exception {
}

ElasticSearch Rest API in JAVA

I am trying to write a simple JAVA REST Client through which I want to PUT/GET elasticsearch document information.
PUT is working fine, my json data got added into index.
But the problem is GET, Response Code is 200, but it is not returning any data.
Can anyone please help.
public static String httpGet(String resturl){
String output = null;
try {
URL url = new URL(resturl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Content-Type", "application/json");
if (conn.getResponseCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ conn.getResponseCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
//System.out.println(output);
}
conn.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return output;
}
I am calling as
RestClient.httpGet("http://localhost:9200/gabsindex/employee/_search")
You println call is currently commented out. If you uncomment it, you'll get the response from the server on one single line, something like
{"took":50,"timed_out":false,"_shards":{"total":5,"successful":5,"failed":0},"hits":{"total":7056,"max_score":1.0,"hits":[...]}}
If you are trying to follow this approach educationally, this can be ok. Remember, nonetheless, that there are a number of libraries that can be used exactly for this use. You should check out the clients page.

Any hints for https form get and post parse html project android?

I'm creating an Android app that should do the following;
Use a form on a https (SSL!) page to login and receive a cookie
Issue httpGET actions to get html
parse that html and show it in a view, list or something.
I've been fooling around with Jsoup, httpUnit and HTMLUnit for quite some time now, but I'm running in to several problems;
A. Login is fine, works.. (I get the website's welcome page) but then, when I issue a GET statement (and include the cookie), I am redirected to the login form. So the response html is not what I expected. (might have something to do with a keepalivestrategy?)
B. InputBuffers are too small to receive entire HTML pages and set them up for parsing.
NB : I do not have control over the webserver
I'm totally new at this, so a tutorial or code snippets would be helpful.
For instance, this is what I use to login to the website :
public int checkLogin() throws Exception {
ArrayList<NameValuePair> data = new ArrayList<NameValuePair>();
data.add(new BasicNameValuePair("userid", getUsername()));
data.add(new BasicNameValuePair("password", getPassword()));
data.add(new BasicNameValuePair("submit_login", "Logmein"));
Log.d(TAG, "Cookie name : " + getCookieName());
Log.d(TAG, "Cookie cont : " + getCookie());
HttpPost request = new HttpPost(BASE_URL);
request.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, false);
request.getParams().setParameter("http.protocol.handle-redirects",false);
request.setEntity(new UrlEncodedFormEntity(data, "UTF-8"));
HttpResponse response;
httpsclient.getCookieStore().clear();
List<Cookie> cookies = httpsclient.getCookieStore().getCookies();
Log.d(TAG, "Number of Cookies pre-login : " + cookies.size());
response = httpsclient.execute(request);
cookies = httpsclient.getCookieStore().getCookies();
Log.d(TAG, "Number of Cookies post-login : " + cookies.size());
String html = "";
// Problem : buffer is too small!
InputStream in = response.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder str = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
str.append(line);
}
in.close();
html = str.toString();
Document doc = Jsoup.parse(html);
Log.v(TAG, "Ik heb nu dit : " + doc.toString());
if (cookies.size() > 0){
storeCookie(cookies.get(0).getName(), cookies.get(0).getValue());
return MensaMobileActivity.REQUEST_SUCCESS;
} else {
return MensaMobileActivity.REQUEST_ERROR;
}
}
You don't handle the SSL certificate at all, that's at least a part of the problem. I struggled starting to learn this recently as well. This block of code will grab the SSL cert from the webpage you're accessing.
try {
URL url = new URL(YOUR_WEBPAGE_HERE);
HttpsURLConnection connect = (HttpsURLConnection)url.openConnection();
connect.connect();
Certificate[] certs = connect.getServerCertificates();
if (certs.length > 0) {
cert = new File("YOUR_PATH_TO_THE_FILE");
//write the certificate obtained to the cert file.
OutputStream os = new FileOutputStream(cert);
os.write(certs[0].getEncoded());
return true;
}
}
catch (SSLPeerUnverifiedException e) {
e.printStackTrace();
}
catch (MalformedURLException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
catch (CertificateEncodingException e) {
e.printStackTrace();
}

Htmlunit mouseOver() does not trigger popup

I wrote the following test. It looks like the htmlunit mouseOver() function is not working (I don't see the html code of the popover).
Am I missing something? How can I solve this issue?
#Test
public void test() throws Exception {
try {
WebClient client = new WebClient(BrowserVersion.FIREFOX_3_6);
HtmlPage currentPage = client.getPage("http://plugins.learningjquery.com/cluetip/demo/");
String xpath = "//a[#title='jTip Style!']";
HtmlElement elm = (HtmlElement) currentPage.getByXPath(xpath).get(0);
xpath = "(//img[#src='kids-drop-sand.jpg'])[1]";
HtmlPage newPage = (HtmlPage) elm.mouseOver();
Assert.assertTrue(newPage.getByXPath(xpath).size() > 0, "Popover is not displayed");
} catch (Exception ex) {
logger.error("Exception thrown in " + this.getClass().toString()
+ " " + ex.getMessage(), ex);
throw ex;
}
}
Did you try with the latest svn ?
http://htmlunit.sourceforge.net/gettingLatestCode.html
Or with the last successed build : http://build.canoo.com/htmlunit/buildresults?log=log20120530150012Lbuild.1963
The latest release available is quite old and manage poorly JS events.

can I use CKEditor in zk(zk WYSIWYG Editor) to upload image?

because use zk upload component to upload a image,then insert the context path of the image to the CKEditor is too complex,
and at http://ckeditor.com/demo, you can see that CKEditor can upload image and flash etc,
but in zk, the CKEditor don't have this feature,
is that mean CKEditor in zk can't upload file?
I'm afraid this is not possible with zk.
I wrote a workaround to do this. You have to add a button to your GUI and add this EventListener to the button:
private class onUpload implements EventListener
{
#Override
public void onEvent(Event event) throws Exception
{
Media media = ((UploadEvent) event).getMedia();
if (media.getContentType().contains("image"))
{
reader.upload(media.getStreamData(), media.getName());
String description = edDescription.getValue();
description += "<img alt=\"\" src=\"/" + media.getName() + "\" />";
edDescription.setValue(description);
}
else
{
new Messagebox().show(_T("You can only upload images!"), _T("Not an image!"), Messagebox.OK, Messagebox.ERROR);
}
}
}
Reader is my class which handles file transfers and is used to write the data to the docroot. In my case the docroot of glassfish 3.1 can be located with the following code. I wrote the method getDocFolder() for ist because it also adds subfolders for each user if they don't already exists.
File file = new File("../docroot/");
This is the code for the upload method of the reader:
InputStream inputStream = null;
try
{
inputStream = new ByteArrayInputStream(imageStream);
String filename = getDocFolder()+"/"+imageName;
File file = new File(filename);
OutputStream out=new FileOutputStream(file);
byte buf[]=new byte[1024];
int len;
while((len = inputStream.read(buf)) > 0)
out.write(buf,0,len);
out.close();
inputStream.close();
}
catch (Exception ex)
{
Logger.getLogger(ImageReader.class.getName()).log(Level.SEVERE, "Error writing image", ex);
}
finally
{
try
{
inputStream.close();
}
catch (IOException ex) {}
}
I hope this helps

Resources