PDA

View Full Version : file upload with extjs 4 with java



rushi2440
20 Mar 2012, 5:32 AM
hi..

forum member I am having some problems with the file upload in extjs 4 and JAVA.

I am using extjs4 and the upload form code is


{
xtype: 'filefield',
margin: '10 0 0 5',
width: 296,
fieldLabel: 'Image',
emptyText: 'Select Company logo...',
id: 'cmplogo',
itemId: 'cmplogo',
name: 'cmplogo',
labelWidth: 70
},
{
xtype: 'button',
margin: '10 0 0 90',
width: 89,
text: 'Upload Image',
action: 'btn-upload-img'
},the button upload image has action:'btn-upload-img' with function defined below


fileUpload: function(btn) {
var win = btn.up('window');
var form = win.down('form').getForm();
alert('VALUE IS :'+form.getValues());

if(form.isValid()){
form.submit({
url : 'company/UploadFile.action',
waitMsg: 'Uploading your file...',
success: function(fp, o) {
Ext.Msg.alert('Success', 'Your file has been uploaded.');
}
});
}
}

and my java controller has below function code


@RequestMapping(value = "/company/UploadFile.action")
public @ResponseBody
Map<String, ? extends Object> uploadFile(UploadItem uploadItem, BindingResult result) throws Exception {
System.out.println("QUERY TO UPLOAD FILE");
try {
if(result.hasErrors()) {
for(ObjectError error: result.getAllErrors()) {
System.err.println("Error: "+error.getCode()+" - "+error.getDefaultMessage());
}
}
else
{
MultipartFile file = uploadItem.getFileData();
String fileName = null;
InputStream inputStream = null;
OutputStream outputStream = null;
if(file.getSize() > 0) {
inputStream = file.getInputStream();
if(file.getSize() > 10000) {
System.out.println("FILE SIZE:::"+file.getSize());
}
System.out.println("SIZE ::"+file.getSize());
fileName = "E:\\images\\"+file.getOriginalFilename();
outputStream = new FileOutputStream(fileName);
System.out.println("FILE NAME AND PATH IS ::"+fileName);
System.out.println("FILENNAME ::"+file.getOriginalFilename());

int readBytes = 0;
byte[] buffer = new byte[10000];
while((readBytes = inputStream.read(buffer, 0, 10000)) !=-1) {
outputStream.write(buffer, 0, readBytes);
}
outputStream.close();
inputStream.close();
}
}


} catch (Exception e) {
return getModelMapError("Error trying to read city");
}
return null;
}

don't know what's wrong with my code above. my firebug console gives me below error


uncaught exception: You're trying to decode an invalid JSON String: <pre>{"message":"Error trying to read city","success":false}</pre>

and my java console gives me null pointer error.

Yogendra Singh
Sr. Programmer
Kintudesigns.com

börn
20 Mar 2012, 5:49 AM
obviously you're getting into
getModelMapError("Error trying to read city"); i because of a null pointer?

You may consider debugging the above method to know which line is wrong and/or log/print the stacktrace of the exception. And you may consider to change the error message - because there is more to fail then reading some city attribute in the code - IO Exceptions e.g.

rushi2440
20 Mar 2012, 9:45 PM
thanks for your response

I had made some changes to my controller, my server side java controller code is below

@RequestMapping(value = "/company/UploadFile.action")
public @ResponseBody String uploadFile(UploadItem uploadItem, BindingResult result) throws Exception {

System.out.println("QUERY TO UPLOAD FILE ");


if (result.hasErrors()) {
for (ObjectError error : result.getAllErrors()) {
System.err.println("Error: " + error.getCode() + " - " + error.getDefaultMessage());
}
return "{success:false}";
}


// Some type of file processing...
System.err.println("-------------------------------------------");
System.err.println("Test upload: " + uploadItem.getFile().getOriginalFilename());
System.err.println("-------------------------------------------");

return "{success:true}";
}


and my extjs controller code is like below

fileUpload: function(btn) { var win = btn.up('window');
var form = win.down('form').getForm();
alert('VALUE IS :' + form.getValues());
if (form.isValid()) {
form.submit({
url: 'company/UploadFile.action',
waitMsg: 'Uploading your file...',
success: function(fp, o) {
Ext.Msg.alert('Success', 'Your file has been uploaded.');
}
});
}
}

my eclipse console throws me error stack trace as below

QUERY TO UPLOAD FILE
-------------------------------------------
Jan 5, 2008 1:06:11 AM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet rms threw exception
java.lang.NullPointerException
at com.kintu.rms.controller.CompanymgtController.uploadFile(CompanymgtController.java:112)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:174)
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:421)
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:409)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:771)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:716)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:644)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:560)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:637)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:293)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:859)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:602)
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
at java.lang.Thread.run(Unknown Source)


I had just try to implement the file upload functionality from the example provided at
http://loianegroner.com/2011/07/extjs-4-file-upload-spring-mvc-3-example/

but don't know for some reason I am not able to implement the upload functionality with my project.

please provide me some useful guidance so I can make file upload working.

Yogendra Singh
Sr. Programmer
Kintudesigns.com

rushi2440
21 Mar 2012, 5:08 AM
After giving a lots of effort I am able to make application which can upload the file for me
below is the index.jsp page


<html>
<head>
<title>Spring FileUpload Example with ExtJS 4 Form</title>


<!-- Ext JS Files -->
<link rel="stylesheet" type="text/css" href="ext-4.0.2a/resources/css/ext-all-gray.css" />
<script type="text/javascript" src="ext-4.0.2a/bootstrap.js"></script>

<!-- file upload form -->
<script src="file-upload.js"></script>


</head>
<body>


<p>Click on "Browse" button (image) to select a file and click on Upload button</p>

<div id="fi-form" style="padding:25px;"></div>
</body>
</html>


and my file-upload.js is

Ext.onReady(function(){


Ext.create('Ext.form.Panel', {
title: 'File Uploader',
width: 400,
bodyPadding: 10,
frame: true,
renderTo: 'fi-form',
items: [{
xtype: 'filefield',
name: 'file',
fieldLabel: 'File',
labelWidth: 50,
msgTarget: 'side',
allowBlank: false,
anchor: '100%',
buttonText: 'Select a File...'
}],
buttons: [{
text: 'Upload',
handler: function() {
var form = this.up('form').getForm();
alert('VALUE IS :'+form.getValues());
if(form.isValid()){
form.submit({
url: 'upload.action',
waitMsg: 'Uploading your file...',
success: function(fp, o) {
Ext.Msg.alert('Success', 'Your file has been uploaded.');
}
});
}
}
}]
});


});


but still I am having problem when I tried to run upload with my complex design view below code is given

Ext.define('rms.view.companymgt.companyAdd',{
extend: 'Ext.window.Window',
alias: 'widget.companyadd',
id: 'companyadd',
itemId: 'companyadd',
height: 634,
width: 822,
modal: true,
resizable: false,
layout: {
type: 'border'
},
title: 'Company',
constrain: true,


initComponent: function() {
var me = this;


Ext.applyIf(me, {
items: [
{
xtype: 'panel',
id: 'mainpanel',
itemId: 'mainpanel',
frame: true,
layout: {
type: 'border'
},
preventHeader: true,
title: 'My Panel',
flex: 3,
region: 'center',
items: [
{
xtype: 'panel',
width: 150,
preventHeader: true,
title: 'My Panel',
flex: 1.5,
region: 'west',
items: [
{
xtype: 'textfield',
id: 'cmptitle',
itemId: 'cmptitle',
margin: 10,
width: 450,
name: 'cmptitle',
fieldLabel: 'Company Title',
labelWidth: 110
},
{
xtype: 'textfield',
id: 'cmpname',
itemId: 'cmpname',
margin: 10,
width: 450,
name: 'cmpname',
fieldLabel: 'Company Name',
labelWidth: 110
},
{
xtype: 'textfield',
id: 'cmpwebsite',
itemId: 'cmpwebsite',
margin: 10,
width: 450,
name: 'cmpwebsite',
fieldLabel: 'Website',
labelWidth: 110
},
{
xtype: 'textfield',
id: 'cmpfax',
itemId: 'cmpfax',
margin: 10,
width: 450,
name: 'cmpfax',
fieldLabel: 'Fax No',
labelWidth: 110
},
{
xtype: 'textfield',
id: 'cmpcontact',
itemId: 'cmpcontact',
margin: 10,
width: 450,
name: 'cmpcontact',
fieldLabel: 'Contact No',
labelWidth: 110
},
{
xtype: 'textfield',
id: 'cmpemail1',
itemId: 'cmpemail1',
margin: 10,
width: 450,
name: 'cmpemail1',
fieldLabel: 'Email Contact',
labelWidth: 110
},
{
xtype: 'textfield',
id: 'cmpemail2',
itemId: 'cmpemail2',
margin: 10,
width: 450,
name: 'cmpemail2',
fieldLabel: 'Other Email',
labelWidth: 110
},
{
xtype: 'combobox',
autoShow: true,
margin: 10,
width: 366,
itemId: 'countryname',
name: 'countryname',
fieldLabel: 'Country',
labelWidth: 110,
emptyText: 'Select Country...',
displayField: 'countryname',
store: 'countryStore',
valueField: 'id'
},
{
xtype: 'button',
margin: '-32 0 0 380',
style: 'position:absolute;',
width: 78,
text: 'Add Country',
action: 'btn-add-country'
},
{
xtype: 'combobox',
id: 'statename',
itemId: 'statename',
margin: 10,
width: 366,
name: 'statename',
fieldLabel: 'State',
labelWidth: 110,
emptyText: 'Select State...',
displayField: 'statename',
store: 'stateStore',
valueField: 'id'
},
{
xtype: 'button',
margin: '-32 0 0 380',
style: 'position:absolute;',
width: 78,
text: 'Add State',
action: 'btn-add-state'
},
{
xtype: 'combobox',
id: 'cityname',
itemId: 'cityname',
margin: 10,
width: 366,
name: 'cityname',
fieldLabel: 'City',
labelWidth: 110,
emptyText: 'Select City...',
displayField: 'cityname',
store: 'cityStore',
valueField: 'id'
},
{
xtype: 'button',
margin: '-32 0 0 380',
style: 'position:absolute;',
width: 78,
text: 'Add City',
action: 'btn-add-city'
},
{
xtype: 'textareafield',
height: 73,
id: 'cmpaddress',
itemId: 'cmpaddress',
margin: 10,
width: 450,
name: 'cmpaddress',
fieldLabel: 'Address',
labelWidth: 110
},
{
xtype: 'htmleditor',
height: 118,
margin: 10,
style: 'background-color: white;',
width: 452,
fieldLabel: 'Description',
labelWidth: 110
}
]
},
{
xtype: 'form',
preventHeader: true,
title: 'My Panel',
flex: 1,
region: 'center',
id: 'centerpanel',
itemId: 'centerpanel',
items: [
{
xtype: 'image',
height: 144,
itemId: 'cmplogoimg',
margin: 10,
width: 287,
src: 'http://www.sencha.com/img/sencha-large.png'
},
{
xtype: 'filefield',
margin: '10 0 0 5',
width: 296,
fieldLabel: 'Image',
emptyText: 'Select Company logo...',
id: 'cmplogo',
itemId: 'cmplogo',
name: 'cmplogo',
labelWidth: 70
},
{
xtype: 'button',
margin: '10 0 0 90',
width: 89,
text: 'Upload Image',
//action: 'btn-upload-img',
handler: function() {
var form = this.up('form').getForm();
alert('VALUE IS :'+form.getValues());
if(form.isValid()){
form.submit({
url: 'upload.action',
waitMsg: 'Uploading your file...',
success: function(fp, o) {
Ext.Msg.alert('Success', 'Your file has been uploaded.');
}
});
}
}
},
{
xtype: 'button',
margin: '10 0 0 30',
width: 89,
text: 'Delete Image',
action: 'btn-delete-img'
}
]
}
]
}
],
dockedItems: [
{
xtype: 'toolbar',
width: 150,
region: 'east',
dock: 'bottom',
items: [
{
xtype: 'tbspacer',
height: 17,
width: 385
},
{
xtype: 'button',
height: 42,
width: 56,
text: 'Save',
action: 'btn-companyadd-data'
},
{
xtype: 'tbseparator'
},
{
xtype: 'button',
height: 42,
width: 56,
text: 'Cancel',
action: 'btn-cancel-data'
}
]
}
]
});


me.callParent(arguments);
}
});


it gives me error. My eclipse error stack trace is like below

INSIDE FILE UPLOAD BEANS
FILE UPLOAD ITEM SI SSLSL ::null
-------------------------------------------
Jan 5, 2008 8:26:42 AM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet resource-mgt threw exception
java.lang.NullPointerException
at com.kintu.resourcemgt.controller.FileUploadController.create(FileUploadController.java:46)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:174)
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:421)
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:409)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:771)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:716)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:644)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:560)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:637)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:293)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:859)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:602)
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
at java.lang.Thread.run(Thread.java:619)



don't able to understand the same code executes perfectly if there is only one function in a controller, but as I tried to use it with multiple function in my controller it throws me an error.

on my server side I am using below code to save the uploaded file

@RequestMapping(value = "/upload.action",method = RequestMethod.POST)
public @ResponseBody String create(FileUploadBean uploadItem, BindingResult result){
System.out.println("FILE UPLOAD ITEM SI SSLSL ::"+uploadItem.getFile());
ExtJSFormResult extjsFormResult = new ExtJSFormResult();

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();
}


// Some type of file processing...
System.err.println("-------------------------------------------");
System.err.println("Test upload: " + uploadItem.getFile().getOriginalFilename());
System.err.println("-------------------------------------------");

try{


MultipartFile file = uploadItem.getFile();
String fileName = null;
InputStream inputStream = null;
OutputStream outputStream = null;
if (file.getSize() > 0) {
inputStream = file.getInputStream();
/*if (file.getSize() > 10000) {
System.out.println("File Size:::" + file.getSize());
extjsFormResult.setSuccess(false);

return extjsFormResult.toString();
}*/
System.out.println("size::" + file.getSize());
fileName = "E:\\images\\"
+ file.getOriginalFilename();
outputStream = new FileOutputStream(fileName);
System.out.println("FILEN ANEM AND PATH IS ::"+fileName);
System.out.println("fileName:" + file.getOriginalFilename());


int readBytes = 0;
byte[] buffer = new byte[40000];
while ((readBytes = inputStream.read(buffer, 0, 40000)) != -1) {
outputStream.write(buffer, 0, readBytes);
}
outputStream.close();
inputStream.close();
}
}catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}

//set extjs return - sucsess
extjsFormResult.setSuccess(true);

return extjsFormResult.toString();
}


please suggest me some solution, as I am not able to understand what's there wrong in my code.
It executes sometime and sometime gives me error.

Yogendra Singh
Sr. Programmer
Kintudesigns.com

lukasw44
24 Aug 2012, 1:39 PM
Hello
i have got the same problem i an using Jboss as 7 .
First of all you must be sure that you have got the same getter / setter method as you have got in your name attrubute .
For example if yout have got extjs attribute :
name: 'file' so you must have got the same getter in your file bean
public void getFile()

public void setFile()

this is my Upload bean item :


public class UploadItem{
private CommonsMultipartFile file;

public CommonsMultipartFile getFile()
{
return file;
}

public void setFile(CommonsMultipartFile file){
this.file = file;
}

}


And my extjs code:

{
xtype: 'filefield',
emptyText: 'Wybierz zdj?cie',
fieldLabel: 'Zdj?cie',
name: 'file',
width: 348,
editable: false,
buttonOnly: true,
id: 'id_uploadButtonPhotoBand',
buttonConfig: {
iconCls: 'upload-icon',
text: 'Dodaj zdj?cie'

}

Also i dont know why but if i add parameter to the RequestMappng : produces="application/json; charset=utf-8", i have got error in firebug but if i delete it i havent got it


I am using the same tutorial

You need add @ResponseBody addnotation