PDA

View Full Version : Getting Error You're trying to decode and invalid JSON String:



Ambuja123
19 Feb 2013, 5:39 AM
I have an requirement to upload a file using extjs 4 and display file details in a table.but i am unable to do in the same time with out refreshing the page and getting error
"
You're trying to decode and invalid JSON String: ".


please some body help me.

my jsp file is



<%@ taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html>
<head>
<title>Upload Blob to database</title>
<style type="text/css">
html, body, div, span, applet, object, iframe, h1, h2, h3, h4, h5, h6, p, blockquote, pre, a, abbr, acronym, address, big, cite, code, del, dfn, em, font, img, ins, kbd, q, s, samp, small, strike, strong, sub, sup, tt, var, b, u, i, center, dl, dt, dd, ol, ul, li, fieldset, form, label, legend, table, caption, tbody, tfoot, thead, tr, th, td, input {
font-size: 100%;
}
body {
font-family: sans-serif;
font-size:12px;
}
.data, .data td {
border-collapse: collapse;
width: 550px;
border: 1px solid #aaa;
padding: 2px;
}
.data th {
background-color: #7CFC00;
color: black;
font-weight: bold;
}
h1, h2, h3 {
font-family: Trebuchet MS,Liberation Sans,DejaVu Sans,sans-serif;
font-weight: bold;
}
h1 {
font-size: 170%;
}
h2 {
font-size: 140%;
}
h3 {
font-size: 120%;
}

</style>


<link rel="stylesheet" type="text/css" href="extjs/resources/css/ext-all.css" />
<script type="text/javascript" src="extjs/bootstrap.js"></script>

<!-- file upload form -->
<!--<script src="js/file-upload.js"></script>
--></head>
<body bgcolor="#DCDCDC">

<h2><font color="red">Upload Files/Documents in Database</font></h2>
<hr>
<h3>Upload new File</h3>
<div id="fi-form" style="padding:25px;">
<script type="text/javascript">
Ext.onReady(function(){

Ext.create('Ext.form.Panel', {
title: 'File Uploader',
width: 400,

bodyPadding: 10,
frame: true,
renderTo: 'fi-form',
defaultType: 'textfield',
items: [
{
xtype: 'textfield',
name: 'name',
fieldLabel: 'File Name',
value: ' Mension File Name',
allowBlank:false
}, {
xtype: 'textareafield',
name: 'description',
fieldLabel: 'File Details',
value: 'Give File Details'
}, {
xtype: 'filefield',
name: 'file',
fieldLabel: 'File',
id: 'file',
msgTarget: 'side',
allowBlank: false,
anchor: '100%',
buttonText: 'Select a File...'
}
],

buttons: [{
text: 'Upload',
handler: function() {
var form = this.up('form').getForm();

if(form.isValid()){
alert("hi");
form.submit({

url: 'save.action',
success: function(fp, o) {
Ext.Msg.alert('Success', 'Your file has been uploaded.');



},
failure: function (form, action) {

switch (action.failureType) {

case Ext.form.action.Action.CLIENT_INVALID:

Ext.Msg.alert('Failure', 'Form fields may not be submitted with invalid values');

break;

case Ext.form.action.Action.CONNECT_FAILURE:

Ext.Msg.alert('Failure', 'Ajax communication failed');

break;

case Ext.form.action.Action.SERVER_INVALID:

Ext.Msg.alert('Failure', action.result.msg);
}

}

});
}
}
}]
});





});
</script>
</div>

<br/>
<hr>
<h3>Uploaded Files/Documents</h3>
<c:if test="${!empty documentList}">
<table class="data" >
<tr>
<th>Filename</th>
<th>FileDetail</th>
<th>&nbsp;</th>
</tr>
<c:forEach items="${documentList}" var="document">
<tr>
<td width="100px">${document.name}</td>
<td width="100px">${document.description}</td>

<td width="20px">
<a href="${pageContext.request.contextPath}/download/${document.id}.action"><img
src="${pageContext.request.contextPath}/img/save_icon.gif" border="0"
title="Download this document"/></a>


<a href="${pageContext.request.contextPath}/remove/${document.id}.action" onclick="return confirm('Are you sure you want to delete this document?')"><img src="${pageContext.request.contextPath}/img/delete_icon.gif" border="0" title="Delete this document" /></a>
</td>
</tr>
</c:forEach>
</table>
</c:if>
<br/>
<hr>
</body>
</html>

and my controller is
package net.devmanuals.controller;

import java.io.IOException;

import java.io.OutputStream;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;

import net.devmanuals.dao.FileDAO;
import net.devmanuals.model.File;

import org.apache.commons.io.IOUtils;
import org.bson.types.ObjectId;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;


import net.devmanuals.model.ExtJSFormResult;

@Controller
public class FileController {

@Autowired
private FileDAO documentDao;

@RequestMapping("/index.action")
public String index(Map<String, Object> map) {
try {
map.put("document", new File());
map.put("documentList", documentDao.list());
map.put("sucess", true);

} catch (Exception e) {
e.printStackTrace();
}

return "save";
}

@RequestMapping(value = "/save.action", method = RequestMethod.POST )
public String save(@ModelAttribute("document") File document,BindingResult result,
@RequestParam("file") MultipartFile file,HttpServletResponse response)throws Exception {

response.setContentType("text/html");
if (result.hasErrors()){
for(ObjectError error : result.getAllErrors()){
System.err.println("Error: " + error.getCode() + " - " + error.getDefaultMessage());
}

//set extjs return - error
extjsFormResult.setSuccess(false);


}

System.out.println("Name:" + document.getName());
System.out.println("Desc:" + document.getDescription());
System.out.println("File:" + file.getName());
System.out.println("ContentType:" + file.getContentType());
List<File> files=null;
try {


document.setFilename(file.getOriginalFilename());
document.setContent(file.getInputStream());
document.setContentType(file.getContentType());
} catch (IOException e) {
e.printStackTrace();
}

try {
files=documentDao.save(document);

} catch (Exception e) {
e.printStackTrace();
}

return "redirect:/index.action";

}

@RequestMapping("/download/{documentId}.action")
public String download(@PathVariable("documentId") ObjectId documentId,
HttpServletResponse response) {

File doc = documentDao.get(documentId);
try {
response.setHeader("Content-Disposition", "attachment;filename=\""
+ doc.getFilename() + "\"");
OutputStream out = response.getOutputStream();
response.setContentType(doc.getContentType());
IOUtils.copy(( doc.getContent()), out);
out.flush();
out.close();

} catch (IOException e) {
e.printStackTrace();
}

return null;
}

@RequestMapping("/remove/{documentId}.action")
public String remove(@PathVariable("documentId") ObjectId documentId) {

documentDao.remove(documentId);

return "redirect:/index.action";
}



}

scottmartin
19 Feb 2013, 1:10 PM
What does your response look like?

Scott.

Ambuja123
21 Feb 2013, 8:45 PM
Thanx Scott for your quick reply

The response what i am getting is




Request URL:
http://localhost:8080/Spring3MvcBlob/save.action
Request Method:
POST
Status Code:
http://www.sencha.com/forum/chrome-devtools://devtools/Images/warningOrangeDot.png302 Moved Temporarily
Request Headersview source

Accept:
text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Charset:
ISO-8859-1,utf-8;q=0.7,*;q=0.3
Accept-Encoding:
gzip,deflate,sdch
Accept-Language:
en-US,en;q=0.8
Cache-Control:
max-age=0
Connection:
keep-alive
Content-Length:
44200
Content-Type:
multipart/form-data; boundary=----WebKitFormBoundary6HCuTTFBVGTTCRhX
Cookie:
JSESSIONID=807398DDECB6307431A360432D431E7D
DNT:
1
Host:
localhost:8080
Origin:
http://localhost:8080
Referer:
http://localhost:8080/Spring3MvcBlob/index.action
User-Agent:
Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1312.57 Safari/537.17

Request Payload

------WebKitFormBoundary6HCuTTFBVGTTCRhX Content-Disposition: form-data; name="name" Mension File Name111112 ------WebKitFormBoundary6HCuTTFBVGTTCRhX Content-Disposition: form-data; name="description" Give File Details1112 ------WebKitFormBoundary6HCuTTFBVGTTCRhX Content-Disposition: form-data; name="file"; filename="Archivist-Archivist (IE9 Issues).docx" Content-Type: application/vnd.openxmlformats-officedocument.wordprocessingml.document ------WebKitFormBoundary6HCuTTFBVGTTCRhX--

Response Headersview source

Content-Language:
en-US
Content-Length:
0
Content-Type:
text/html;charset=ISO-8859-1
Date:
Fri, 22 Feb 2013 04:41:04 GMT
Location:
http://localhost:8080/Spring3MvcBlob/index.action
Server:
Apache-Coyote/1.1

Ambuja123
22 Feb 2013, 1:14 AM
Sorry Scott That is the header what i have pasted before actually my response looks like this



<html> <head> <title>Upload Blob to database</title> <style type="text/css"> html, body, div, span, applet, object, iframe, h1, h2, h3, h4, h5, h6, p, blockquote, pre, a, abbr, acronym, address, big, cite, code, del, dfn, em, font, img, ins, kbd, q, s, samp, small, strike, strong, sub, sup, tt, var, b, u, i, center, dl, dt, dd, ol, ul, li, fieldset, form, label, legend, table, caption, tbody, tfoot, thead, tr, th, td, input { font-size: 100%; } body { font-family: sans-serif; font-size:12px; } .data, .data td { border-collapse: collapse; width: 550px; border: 1px solid #aaa; padding: 2px; } .data th { background-color: #7CFC00; color: black; font-weight: bold; } h1, h2, h3 { font-family: Trebuchet MS,Liberation Sans,DejaVu Sans,sans-serif; font-weight: bold; } h1 { font-size: 170%; } h2 { font-size: 140%; } h3 { font-size: 120%; } </style> <link rel="stylesheet" type="text/css" href="extjs/resources/css/ext-all.css" /> <script type="text/javascript" src="extjs/bootstrap.js"></script> <!-- file upload form --> <!--<script src="js/file-upload.js"></script> --></head> <body bgcolor="#DCDCDC">

<h2><font color="red">Upload Files/Documents in Database</font></h2> <hr> <h3>Upload new File</h3> <div id="fi-form" style="padding:25px;"> <script type="text/javascript"> Ext.onReady(function(){ Ext.create('Ext.form.Panel', { title: 'File Uploader', width: 400, bodyPadding: 10, frame: true, renderTo: 'fi-form', defaultType: 'textfield', items: [ { xtype: 'textfield', name: 'name', fieldLabel: 'File Name', value: ' Mension File Name', allowBlank:false }, { xtype: 'textareafield', name: 'description', fieldLabel: 'File Details', value: 'Give File Details' }, { xtype: 'filefield', name: 'file', fieldLabel: 'File', id: 'file', msgTarget: 'side', allowBlank: false, anchor: '100%', buttonText: 'Select a File...' } ], buttons: [{ text: 'Upload', handler: function() { var form = this.up('form').getForm(); if(form.isValid()){ alert("hi"); form.submit({ url: 'save.action', success: function(fp, o) {
Ext.Msg.alert('Success', 'Your file has been uploaded.'); }, failure: function (form, action) { switch (action.failureType) { case Ext.form.action.Action.CLIENT_INVALID: Ext.Msg.alert('Failure', 'Form fields may not be submitted with invalid values'); break; case Ext.form.action.Action.CONNECT_FAILURE: Ext.Msg.alert('Failure', 'Ajax communication failed'); break; case Ext.form.action.Action.SERVER_INVALID: Ext.Msg.alert('Failure', action.result.msg); } } }); } } }] }); Ext.Ajax.on('requestexception', function(response, options, e) { Ext.Msg.show(); // Make sure original failure and callback handlers aren't called delete options.failure; delete options.callback; }); }); </script> </div> <br/> <hr> <h3>Uploaded Files/Documents</h3>


<table class="data" >
<tr>
<th>Filename</th>
<th>FileDetail</th>
<th>&nbsp;</th>
</tr>


<tr>
<td width="100px"> Mension File Name1</td>
<td width="100px">Give File 1</td>

<td width="20px">
<a href="/Spring3MvcBlob/download/512730562ba5abd93c2bde66.action (http://localhost:8080/Spring3MvcBlob/download/512730562ba5abd93c2bde66.action)"><img
src="/Spring3MvcBlob/img/save_icon.gif" border="0"
title="Download this document"/></a>


<a href="/Spring3MvcBlob/remove/512730562ba5abd93c2bde66.action (http://localhost:8080/Spring3MvcBlob/remove/512730562ba5abd93c2bde66.action)" onclick="return confirm('Are you sure you want to delete this document?')"><img src="/Spring3MvcBlob/img/delete_icon.gif (http://localhost:8080/Spring3MvcBlob/img/delete_icon.gif)" border="0" title="Delete this document" /></a>
</td>
</tr>


<tr>
<td width="100px"> Mension File Name2</td>
<td width="100px">Give File Details2</td>

<td width="20px">
<a href="/Spring3MvcBlob/download/512731572ba5eafb73ec2026.action (http://localhost:8080/Spring3MvcBlob/download/512731572ba5eafb73ec2026.action)"><img
src="/Spring3MvcBlob/img/save_icon.gif" border="0"
title="Download this document"/></a>


<a href="/Spring3MvcBlob/remove/512731572ba5eafb73ec2026.action (http://localhost:8080/Spring3MvcBlob/remove/512731572ba5eafb73ec2026.action)" onclick="return confirm('Are you sure you want to delete this document?')"><img src="/Spring3MvcBlob/img/delete_icon.gif (http://localhost:8080/Spring3MvcBlob/img/delete_icon.gif)" border="0" title="Delete this document" /></a>
</td>
</tr>


<tr>
<td width="100px"> Mension File Name3</td>
<td width="100px">Give File Details3</td>

<td width="20px">
<a href="/Spring3MvcBlob/download/5127348e2ba598442c6b8791.action (http://localhost:8080/Spring3MvcBlob/download/5127348e2ba598442c6b8791.action)"><img
src="/Spring3MvcBlob/img/save_icon.gif" border="0"
title="Download this document"/></a>


<a href="/Spring3MvcBlob/remove/5127348e2ba598442c6b8791.action (http://localhost:8080/Spring3MvcBlob/remove/5127348e2ba598442c6b8791.action)" onclick="return confirm('Are you sure you want to delete this document?')"><img src="/Spring3MvcBlob/img/delete_icon.gif (http://localhost:8080/Spring3MvcBlob/img/delete_icon.gif)" border="0" title="Delete this document" /></a>
</td>
</tr>


</table>


<br/>
<hr>
</body>
</html>
I am getting my jsp file totally.

Ambuja123
22 Feb 2013, 1:23 AM
If I am changing my controller like this

package net.devmanuals.controller;

import java.io.IOException;

import java.io.OutputStream;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;

import net.devmanuals.dao.FileDAO;
import net.devmanuals.model.File;

import org.apache.commons.io.IOUtils;
import org.bson.types.ObjectId;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;


import net.devmanuals.model.ExtJSFormResult;

@Controller
public class FileController {

@Autowired
private FileDAO documentDao;
ExtJSFormResult extjsFormResult = new ExtJSFormResult();
@RequestMapping("/index.action")
public String index(Map<String, Object> map) {
try {
map.put("document", new File());
map.put("documentList", documentDao.list());
map.put("sucess", true);
System.out.println(map.toString());
} catch (Exception e) {
e.printStackTrace();
}
//extjsFormResult.setSuccess(true);
//return extjsFormResult.toString();
return "save";
}

@RequestMapping(value = "/save.action", method = RequestMethod.POST )
public @ResponseBody Map<String, Object> save(@ModelAttribute("document") File document,BindingResult result,
@RequestParam("file") MultipartFile file,HttpServletResponse response)throws Exception {

response.setContentType("text/html");
if (result.hasErrors()){
for(ObjectError error : result.getAllErrors()){
System.err.println("Error: " + error.getCode() + " - " + error.getDefaultMessage());
}

//set extjs return - error
extjsFormResult.setSuccess(false);

//return extjsFormResult.toString();
}

System.out.println("Name:" + document.getName());
System.out.println("Desc:" + document.getDescription());
System.out.println("File:" + file.getName());
System.out.println("ContentType:" + file.getContentType());
List<File> files=null;
try {
//Blob blob = Hibernate.createBlob(file.getInputStream());
/* HttpServletResponseWrapper wrapper = new HttpServletResponseWrapper(response);
wrapper.setContentType("text/html;charset=UTF-8"); */
document.setFilename(file.getOriginalFilename());
document.setContent(file.getInputStream());
document.setContentType(file.getContentType());
} catch (IOException e) {
e.printStackTrace();
}

try {
files=documentDao.save(document);

} catch (Exception e) {
e.printStackTrace();
}

return getMap(files);

}

@RequestMapping("/download/{documentId}.action")
public String download(@PathVariable("documentId") ObjectId documentId,
HttpServletResponse response) {

File doc = documentDao.get(documentId);
try {
response.setHeader("Content-Disposition", "attachment;filename=\""
+ doc.getFilename() + "\"");
OutputStream out = response.getOutputStream();
response.setContentType(doc.getContentType());
IOUtils.copy(( doc.getContent()), out);
out.flush();
out.close();

} catch (IOException e) {
e.printStackTrace();
}

return null;
}

@RequestMapping("/remove/{documentId}.action")
public String remove(@PathVariable("documentId") ObjectId documentId) {

documentDao.remove(documentId);

return "redirect:/index.action";
}
public ResponseEntity<String> handleAJAX() {
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.add("Content-Type", "text/html; charset=utf-8");

//some stuff here to produce output
return new ResponseEntity<String>("{\"success\":true}", responseHeaders, HttpStatus.CREATED);
}

private Map<String,Object> getMap(List<File> files){

Map<String,Object> modelMap = new HashMap<String,Object>(4);
modelMap.put("document", new File());
modelMap.put("documentList", files);
modelMap.put("success", true);

return modelMap;
}





}


Then I m getting 406 Not Acceptable.

Ambuja123
22 Feb 2013, 1:37 AM
If I am writing my controller like this .

package net.devmanuals.controller;

import java.io.IOException;

import java.io.OutputStream;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;

import net.devmanuals.dao.FileDAO;
import net.devmanuals.model.File;

import org.apache.commons.io.IOUtils;
import org.bson.types.ObjectId;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;


import net.devmanuals.model.ExtJSFormResult;

@Controller
public class FileController {

@Autowired
private FileDAO documentDao;
ExtJSFormResult extjsFormResult = new ExtJSFormResult();
@RequestMapping("/index.action")
public String index(Map<String, Object> map) {
try {
map.put("document", new File());
map.put("documentList", documentDao.list());
map.put("sucess", true);
System.out.println(map.toString());
} catch (Exception e) {
e.printStackTrace();
}
//extjsFormResult.setSuccess(true);
//return extjsFormResult.toString();
return "save";
}

@RequestMapping(value = "/save.action", method = RequestMethod.POST )
public void save(@ModelAttribute("document") File document,BindingResult result,
@RequestParam("file") MultipartFile file,HttpServletResponse response)throws Exception {

response.setContentType("text/html");
if (result.hasErrors()){
for(ObjectError error : result.getAllErrors()){
System.err.println("Error: " + error.getCode() + " - " + error.getDefaultMessage());
}

//set extjs return - error
extjsFormResult.setSuccess(false);

//return extjsFormResult.toString();
}

System.out.println("Name:" + document.getName());
System.out.println("Desc:" + document.getDescription());
System.out.println("File:" + file.getName());
System.out.println("ContentType:" + file.getContentType());
List<File> files=null;
try {

document.setFilename(file.getOriginalFilename());
document.setContent(file.getInputStream());
document.setContentType(file.getContentType());
} catch (IOException e) {
e.printStackTrace();
}

try {
files=documentDao.save(document);

} catch (Exception e) {
e.printStackTrace();
}

StringBuffer result1 = new StringBuffer();
try
{

//server side operation


result1.append("{");
result1.append("'success':true").append(",");
result1.append("'msg':'File uploaded successfully22222.'").append(",");
result1.append("'documentList':'").append(documentDao.list()).append("',");
result1.append("'document':'").append(new File()).append("',");

result1.append("}");


}
catch (Exception e)
{



result1.append("{");
result1.append("'success':false").append(",");
result1.append("'msg':'File uploaded failed.'").append(",");

result1.append("}");
}


System.out.println(result1.toString());
result1.append("</body></html>");
response.getWriter().print(result1.toString());

}

@RequestMapping("/download/{documentId}.action")
public String download(@PathVariable("documentId") ObjectId documentId,
HttpServletResponse response) {

File doc = documentDao.get(documentId);
try {
response.setHeader("Content-Disposition", "attachment;filename=\""
+ doc.getFilename() + "\"");
OutputStream out = response.getOutputStream();
response.setContentType(doc.getContentType());
IOUtils.copy(( doc.getContent()), out);
out.flush();
out.close();

} catch (IOException e) {
e.printStackTrace();
}

return null;
}

@RequestMapping("/remove/{documentId}.action")
public String remove(@PathVariable("documentId") ObjectId documentId) {

documentDao.remove(documentId);

return "redirect:/index.action";
}
public ResponseEntity<String> handleAJAX() {
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.add("Content-Type", "text/html; charset=utf-8");

//some stuff here to produce output
return new ResponseEntity<String>("{\"success\":true}", responseHeaders, HttpStatus.CREATED);
}

private Map<String,Object> getMap(List<File> files){

Map<String,Object> modelMap = new HashMap<String,Object>(4);
modelMap.put("document", new File());
modelMap.put("documentList", files);
modelMap.put("success", true);

return modelMap;
}





}


Then I am getting the correct response
{'success':true,'msg':'File uploaded successfully22222.','documentList':'[[email protected]ac821]','document':'[email protected]',}</body></html>

but the table is not updating with out refresh

Ambuja123
22 Feb 2013, 1:38 AM
Dear Scott please Response me.

Ambuja123
22 Feb 2013, 1:43 AM
Dear Scott please Response me.


If I m changing my controller to like this
package net.devmanuals.controller;

import java.io.IOException;

import java.io.OutputStream;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;

import net.devmanuals.dao.FileDAO;
import net.devmanuals.model.File;

import org.apache.commons.io.IOUtils;
import org.bson.types.ObjectId;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;


import net.devmanuals.model.ExtJSFormResult;

@Controller
public class FileController {

@Autowired
private FileDAO documentDao;
ExtJSFormResult extjsFormResult = new ExtJSFormResult();
@RequestMapping("/index.action")
public String index(Map<String, Object> map) {
try {
map.put("document", new File());
map.put("documentList", documentDao.list());
map.put("sucess", true);
System.out.println(map.toString());
} catch (Exception e) {
e.printStackTrace();
}
//extjsFormResult.setSuccess(true);
//return extjsFormResult.toString();
return "save";
}

@RequestMapping(value = "/save.action", method = RequestMethod.POST )
public void save(@ModelAttribute("document") File document,BindingResult result,
@RequestParam("file") MultipartFile file,HttpServletResponse response)throws Exception {

response.setContentType("text/html");
if (result.hasErrors()){
for(ObjectError error : result.getAllErrors()){
System.err.println("Error: " + error.getCode() + " - " + error.getDefaultMessage());
}


}

System.out.println("Name:" + document.getName());
System.out.println("Desc:" + document.getDescription());
System.out.println("File:" + file.getName());
System.out.println("ContentType:" + file.getContentType());
List<File> files=null;
try {

document.setFilename(file.getOriginalFilename());
document.setContent(file.getInputStream());
document.setContentType(file.getContentType());
} catch (IOException e) {
e.printStackTrace();
}

try {
files=documentDao.save(document);

} catch (Exception e) {
e.printStackTrace();
}

StringBuffer result1 = new StringBuffer();
try
{

//server side operation


result1.append("{");
result1.append("'success':true").append(",");
result1.append("'msg':'File uploaded successfully22222.'").append(",");
result1.append("'documentList':'").append(documentDao.list()).append("',");
result1.append("'document':'").append(new File()).append("',");

result1.append("}");


}
catch (Exception e)
{



result1.append("{");
result1.append("'success':false").append(",");
result1.append("'msg':'File uploaded failed.'").append(",");

result1.append("}");
}


System.out.println(result1.toString());
result1.append("</body></html>");
response.getWriter().print(result1.toString());




}

@RequestMapping("/download/{documentId}.action")
public String download(@PathVariable("documentId") ObjectId documentId,
HttpServletResponse response) {

File doc = documentDao.get(documentId);
try {
response.setHeader("Content-Disposition", "attachment;filename=\""
+ doc.getFilename() + "\"");
OutputStream out = response.getOutputStream();
response.setContentType(doc.getContentType());
IOUtils.copy(( doc.getContent()), out);
out.flush();
out.close();

} catch (IOException e) {
e.printStackTrace();
}

return null;
}

@RequestMapping("/remove/{documentId}.action")
public String remove(@PathVariable("documentId") ObjectId documentId) {

documentDao.remove(documentId);

return "redirect:/index.action";
}
public ResponseEntity<String> handleAJAX() {
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.add("Content-Type", "text/html; charset=utf-8");

//some stuff here to produce output
return new ResponseEntity<String>("{\"success\":true}", responseHeaders, HttpStatus.CREATED);
}

private Map<String,Object> getMap(List<File> files){

Map<String,Object> modelMap = new HashMap<String,Object>(4);
modelMap.put("document", new File());
modelMap.put("documentList", files);
modelMap.put("success", true);

return modelMap;
}
}

Then I am getting the response like this

{'success':true,'msg':'File uploaded successfully22222.','documentList':'[[email protected]]','document':'[email protected]',}</body></html>


but table is not updating without refresh

scottmartin
22 Feb 2013, 5:28 AM
Sorry for the delay .. you posts were getting moderated, so I was not alerted ..

as for the json .. you have some errors:

yours:


{
'success': true,
'msg': 'Fileuploadedsuccessfully22222.',
'documentList': '[
[email protected]
]',
'document': '[email protected]',

}


updated: checked with: http://jsonlint.com/


{
"success": true,
"msg": "Fileuploadedsuccessfully22222.",
"documentList": [
"[email protected]"
],
"document": "[email protected]"
}


I changed quotes for testing to validate, but single quotes will work as well in app.

Scott

Ambuja123
22 Feb 2013, 9:40 PM
Thanks for your reply Scott according to you said i changed my json returning from server by changing my controller like this

@RequestMapping(value = "/save.action", method = RequestMethod.POST )
public @ResponseBody void save(@ModelAttribute("document") File document,BindingResult result,
@RequestParam("file") MultipartFile file,HttpServletResponse response)throws Exception {

response.setContentType("text/html");
if (result.hasErrors()){
for(ObjectError error : result.getAllErrors()){
System.err.println("Error: " + error.getCode() + " - " + error.getDefaultMessage());
}

//set extjs return - error
extjsFormResult.setSuccess(false);

//return extjsFormResult.toString();
}

System.out.println("Name:" + document.getName());
System.out.println("Desc:" + document.getDescription());
System.out.println("File:" + file.getName());
System.out.println("ContentType:" + file.getContentType());
List<File> files=null;
try {

document.setFilename(file.getOriginalFilename());
document.setContent(file.getInputStream());
document.setContentType(file.getContentType());
} catch (IOException e) {
e.printStackTrace();
}


try {
files=documentDao.save(document);

} catch (Exception e) {
e.printStackTrace();
}

StringBuffer result1 = new StringBuffer();
try
{


//server side operation



result1.append("{");
result1.append("\"success\":true").append(",");
result1.append("\"msg\":\"File uploaded successfully22222.\"").append(",");
result1.append("\"documentList\":\"").append(documentDao.list()).append("\",");
result1.append("\"document\":\"").append(new File()).append("\",");

result1.append("}");




}
catch (Exception e)
{ }




System.out.println(result1.toString());

response.getWriter().print(result1.toString());

}


but still I am unable to update my table with out refresh can you please see my jsp page that is correct or not.
my jsp page is


<%@ taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html>
<head>
<title>Upload Blob to database</title>
<style type="text/css">
html, body, div, span, applet, object, iframe, h1, h2, h3, h4, h5, h6, p, blockquote, pre, a, abbr, acronym, address, big, cite, code, del, dfn, em, font, img, ins, kbd, q, s, samp, small, strike, strong, sub, sup, tt, var, b, u, i, center, dl, dt, dd, ol, ul, li, fieldset, form, label, legend, table, caption, tbody, tfoot, thead, tr, th, td, input {
font-size: 100%;
}
body {
font-family: sans-serif;
font-size:12px;
}
.data, .data td {
border-collapse: collapse;
width: 550px;
border: 1px solid #aaa;
padding: 2px;
}
.data th {
background-color: #7CFC00;
color: black;
font-weight: bold;
}
h1, h2, h3 {
font-family: Trebuchet MS,Liberation Sans,DejaVu Sans,sans-serif;
font-weight: bold;
}
h1 {
font-size: 170%;
}
h2 {
font-size: 140%;
}
h3 {
font-size: 120%;
}

</style>


<link rel="stylesheet" type="text/css" href="extjs/resources/css/ext-all.css" />
<script type="text/javascript" src="extjs/bootstrap.js"></script>

<!-- file upload form -->
<!--<script src="js/file-upload.js"></script>
--></head>
<body bgcolor="#DCDCDC">


<h2><font color="red">Upload Files/Documents in Database</font></h2>
<hr>
<h3>Upload new File</h3>
<div id="fi-form" style="padding:25px;">
<script type="text/javascript">
Ext.onReady(function(){


Ext.create('Ext.form.Panel', {
title: 'File Uploader',
width: 400,
method:'POST',
bodyPadding: 10,
frame: true,
renderTo: 'fi-form',
defaultType: 'textfield',
items: [
{
xtype: 'textfield',
name: 'name',
fieldLabel: 'File Name',
value: ' Mension File Name',
allowBlank:false
}, {
xtype: 'textareafield',
name: 'description',
fieldLabel: 'File Details',
value: 'Give File Details'
}, {
xtype: 'filefield',
name: 'file',
fieldLabel: 'File',
id: 'file',
msgTarget: 'side',
allowBlank: false,
anchor: '100%',
buttonText: 'Select a File...'
}
],


buttons: [{
text: 'Upload',
handler: function() {
var form = this.up('form').getForm();

if(form.isValid()){
alert("hi");
form.submit({
method:'POST',
url: 'save.action',
success: function(fp, o) {
Ext.Msg.alert('Success', 'Your file has been uploaded.');




},
failure: function (form, action) {

switch (action.failureType) {

case Ext.form.action.Action.CLIENT_INVALID:

Ext.Msg.alert('Failure', 'Form fields may not be submitted with invalid values');

break;

case Ext.form.action.Action.CONNECT_FAILURE:

Ext.Msg.alert('Failure', 'Ajax communication failed');

break;

case Ext.form.action.Action.SERVER_INVALID:

Ext.Msg.alert('Failure', action.result.msg);
}

}


});
}
}
}]
});







});
</script>
</div>


<br/>
<hr>
<h3>Uploaded Files/Documents</h3>
<c:if test="${!empty documentList}">
<table class="data" >
<tr>
<th>Filename</th>
<th>FileDetail</th>
<th>&nbsp;</th>
</tr>
<c:forEach items="${documentList}" var="document">
<tr>
<td width="100px">${document.name}</td>
<td width="100px">${document.description}</td>

<td width="20px">
<a href="${pageContext.request.contextPath}/download/${document.id}.action"><img
src="${pageContext.request.contextPath}/img/save_icon.gif" border="0"
title="Download this document"/></a>


<a href="${pageContext.request.contextPath}/remove/${document.id}.action" onclick="return confirm('Are you sure you want to delete this document?')"><img src="${pageContext.request.contextPath}/img/delete_icon.gif" border="0" title="Delete this document" /></a>
</td>
</tr>
</c:forEach>
</table>
</c:if>
<br/>
<hr>
</body>
</html>

Ambuja123
24 Feb 2013, 8:17 PM
Please anybody can reply me.....

scottmartin
25 Feb 2013, 5:04 AM
Post your return JSON.

Ambuja123
25 Feb 2013, 5:07 AM
My Return json is


{ "success": true, "msg": "Fileuploadedsuccessfully22222.", "documentList": [ "[email protected]" ], "document": "[email protected]" }