Grails file upload Kendoui - grails

can someone please tell me a running example of upload file in kendoui?
As I have tried to upload file and its uploading in view page but when I click on save button I can't find that file in show page.I searched on it on internet then I found some problem of server.So someone please tell me how to use server in my case.I'm working on a grails project
Code That I have Used.:--
<tr class="prop">
<td valign="top" class="name">
<label>File Upload</label>
<input name="photos[]" id="photos" type="file" /><script>$(document).ready(function ()$("#photos").kendoUpload({
autoUpload:true,
upload: onUpload,
error: onError
});
function onError(e) {
// Array with information about the uploaded files
var files = e.files;
if (e.operation == "upload") {
alert("Failed to uploaded " + files.length + " files");
}
// Suppress the default error message
e.preventDefault();
},
function onUpload(e) {
var files = e.files;
if (e.operation == "upload") {
alert("Successfully uploaded " + files.length + " files");
}
});</script>
</td>
</tr>
i'm ading the view file :- create.gsp
<%# page import="ten.SkeletonBill"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta name="layout" content="billing" />
<get var="entityName"
value="${message(code: 'skeletonBill.label', default: 'SkeletonBill')}" />
<title><g:message code="default.create.label"
args="[entityName]" /></title>
<script src="source/kendo.all.js"></script>
<link href="styles/kendo.common.css" rel="stylesheet" />
<link href="styles/kendo.default.css" rel="stylesheet" />
</head>
<body>
<content tag="menu-function">
<li><span class="k-link"><a href="#"
onclick="SkeletonBillForm.submit();return false;"><i
class="icon-plus-sign"></i>
<g:message code="default.button.save.label" /></a></span></li>
</content>
<div class="body">
<h1>
<g:message code="default.create.label" args="[entityName]" />
</h1>
<g:if test="${flash.message}">
<div class="message">
${flash.message}
</div>
</g:if>
<g:hasErrors bean="${skeletonBillInstance}">
<div class="alert alert-error">
<a class="close" data-dismiss="alert">×</a>
<g:renderErrors bean="${skeletonBillInstance}" as="list" />
</div>
</g:hasErrors>
<g:uploadForm name="SkeletonBillForm" action="save" method="post">
<div class="dialog">
<table>
<tbody>
<tr class="prop">
<td valign="top" class="name"><label for="bones"><g:message
code="skeletonBill.bones.label" default="Bones" /></label></td>
<td valign="top"
class="value ${hasErrors(bean: skeletonBillInstance, field: 'bones', 'errors')}">
<g:textField name="bones"
value="${fieldValue(bean: skeletonBillInstance, field: 'bones')}" />
</td>
</tr>
<tr class="prop">
<td valign="top" class="name"><label for="dateOfBirth"><g:message
code="skeletonBill.dateOfBirth.label" default="Date Of Birth" /></label>
</td>
<td valign="top"
class="value ${hasErrors(bean: skeletonBillInstance, field: 'dateOfBirth', 'errors')}">
<g:textField name="dateOfBirth"
value="${skeletonBillInstance?.dateOfBirth}" /> <script>$(document).ready(function () {$("#dateOfBirth").kendoDatePicker({format:"yyyy-MM-dd"})});</script>
</td>
</tr>
<tr class="prop">
<td valign="top" class="name">
<label>File Upload</label>
<input name="excelSheet" id="excelSheet" type="file" />
<script>
$(document).ready(function() {
$("#excelSheet").kendoUpload();
},
function onError(e) {
// Array with information about the uploaded files
var files = e.files;
if (e.operation == "upload") {
alert("Failed to uploaded " + files.length + " files");
}
// Suppress the default error message
e.preventDefault();
},
function onUpload(e) {
var files = e.files;
if (e.operation == "upload") {
alert("Successfully uploaded " + files.length + " files");
}
});
</script>
</td>
</tr>
</tbody>
</table>
</div>
</g:uploadForm>
</div>
</body>
</html>
And Also Controller.gsp
def save = {
def skeletonBillInstance = new SkeletonBill(params)
if(!skeletonBillInstance.empty){
println "Name: ${skeletonBill.bones}"
flash.message = "${message(code: 'default.created.message', args: [message(code: 'skeletonBill.label', default: 'SkeletonBill'), skeletonBillInstance.id])}"
redirect(action: "show", id: skeletonBillInstance.id)
}
} else {
render(view: "create", model: [skeletonBillInstance: skeletonBillInstance])
}
}

Couple of things
1) If you want to use KendoUI, I wouldn't use the gsp tags. Please use the normal form tags to define your form, if you do this grails resorts to using the prototype plugin for.
2) I will not mix the script code with the tags.
3) If you are using grails 2.0, you can use the KendoUI plugin, you can find more information at http://grails.org/plugin/kendo-ui
Hope that helps.

Related

Grails Parent Child Form not saving child data

I am trying to create a parent child form with Author and Book domain classes. The view works fine and lets me enter books when I creating a new Author. However, when I add a new author and the books and check the database (dbconsole), I see a new record in the Author table but no records are added to the Book table. Can you please let me know what I am missing or doing wrong here?
Here are my domain classes:
AUTHOR:
package bookauthor1tomany
import org.apache.common.collections.list.*
import org.apache.commons.collections.ListUtils.*
class Author {
static constraints = {
}
String name
String category
List<Book> books = new ArrayList<>()
static hasMany = [ books:Book ]
static mapping = {
books cascade:"all-delete-orphan"
}
def getExpandableBookList() {
return LazyList.decorate(books, FactoryUtils.instantiateFactory(Book.class))
}
String toString(){
return "${name}" - "${category}"
}
}
BOOK
package bookauthor1tomany
class Book {
static constraints = {
}
String title
boolean _deleted
static transients = [ '_deleted' ]
static belongsTo = [ author:Author ]
def String toString() {
return title
}
}
AuthorController
I haven't changed anything with the controller. This is the default generated save method for the Author controller.
#Transactional
def save(Author authorInstance) {
if (authorInstance == null) {
notFound()
return
}
if (authorInstance.hasErrors()) {
respond authorInstance.errors, view:'create'
return
}
authorInstance.save flush:true
request.withFormat {
form multipartForm {
flash.message = message(code: 'default.created.message', args: [message(code: 'author.label', default: 'Author'), authorInstance.id])
redirect authorInstance
}
'*' { respond authorInstance, [status: CREATED] }
}
}
GSPs
create.gsp
<!DOCTYPE html>
<html>
<head>
<meta name="layout" content="main">
<g:set var="entityName" value="${message(code: 'author.label', default: 'Author')}" />
<title><g:message code="default.create.label" args="[entityName]" /></title>
</head>
<body>
<g:message code="default.link.skip.label" default="Skip to content…"/>
<div class="nav" role="navigation">
<ul>
<li><a class="home" href="${createLink(uri: '/')}"><g:message code="default.home.label"/></a></li>
<li><g:link class="list" action="index"><g:message code="default.list.label" args="[entityName]" /></g:link></li>
</ul>
</div>
<div id="create-author" class="content scaffold-create" role="main">
<h1><g:message code="default.create.label" args="[entityName]" /></h1>
<g:if test="${flash.message}">
<div class="message" role="status">${flash.message}</div>
</g:if>
<g:hasErrors bean="${authorInstance}">
<ul class="errors" role="alert">
<g:eachError bean="${authorInstance}" var="error">
<li <g:if test="${error in org.springframework.validation.FieldError}">data-field-id="${error.field}"</g:if>><g:message error="${error}"/></li>
</g:eachError>
</ul>
</g:hasErrors>
<g:form url="[resource:authorInstance, action:'save']" >
<fieldset class="form">
<g:render template="authortemp"/>
</fieldset>
<fieldset class="buttons">
<g:submitButton name="create" class="save" value="${message(code: 'default.button.create.label', default: 'Create')}" />
</fieldset>
</g:form>
</div>
</body>
</html>
_form.gsp
<%# page import="BookAuthor1ToMany" %>
<div class="fieldcontain ${hasErrors(bean: authorInstance, field: 'books', 'error')} ">
<label for="books">
<g:message code="author.books.label" default="Books" />
</label>
<ul class="one-to-many">
<g:each in="${authorInstance?.books?}" var="b">
<li><g:link controller="book" action="show" id="${b.id}">${b?.encodeAsHTML()}</g:link></li>
</g:each>
<li class="add">
<g:link controller="book" action="create" params="['author.id': authorInstance?.id]">${message(code: 'default.add.label', args: [message(code: 'book.label', default: 'Book')])}</g:link>
</li>
</ul>
</div>
<div class="fieldcontain ${hasErrors(bean: authorInstance, field: 'name', 'error')} required">
<label for="name">
<g:message code="author.name.label" default="Name" />
<span class="required-indicator">*</span>
</label>
<g:textField name="name" required="" value="${authorInstance?.name}"/>
</div>
_authortemp.gsp
<div class="dialog">
<table>
<tbody>
<tr class="prop">
<td valign="top" class="name"><label for="name">Name:</label></td>
<td valign="top" class="value ${hasErrors(bean:authorInstance,field:'name','errors')}">
<input type="text" id="name" name="name" value="${fieldValue(bean:authorInstance,field:'name')}"/>
</td>
</tr>
<tr class="prop">
<td valign="top" class="name"><label for="category">Category:</label></td>
<td valign="top" class="value ${hasErrors(bean:authorInstance,field:'category','errors')}">
<input type="text" id="category" name="category" value="${fieldValue(bean:authorInstance,field:'category')}"/>
</td>
</tr>
<tr class="prop">
<td valign="top" class="name"><label for="books">Books:</label></td>
<td valign="top" class="value ${hasErrors(bean:authorInstance,field:'books','errors')}">
<g:render template="books" model="['authorInstance':authorInstance]" />
</td>
</tr>
</tbody>
</table>
</div>
_books.gsp
<script type="text/javascript">
var childCount = ${authorInstance?.books.size()} + 0;
function addChild() {
var htmlId = "book" + childCount;
var deleteIcon = "${resource(dir:'images/skin', file:'database_delete.png')}";
var templateHtml = "<div id='" + htmlId + "' name='" + htmlId + "'>\n";
templateHtml += "<input type='text' id='expandableBookList[" + childCount + "].title' name='expandableBookList[" + childCount + "].title' />\n";
templateHtml += "<span onClick='$(\"#" + htmlId + "\").remove();'><img src='" + deleteIcon + "' /></span>\n";
templateHtml += "</div>\n";
$("#childList").append(templateHtml);
childCount++;
}
</script>
<div id="childList">
<g:each var="book" in="${authorInstance.books}" status="i">
<g:render template='book' model="['book':book,'i':i]"/>
</g:each>
</div>
<input type="button" value="Add Book" onclick="addChild();" />
_book.gsp
<div id="book${i}">
<g:hiddenField name='expandableBookList[${i}].id' value='${book.id}'/>
<g:textField name='expandableBookList[${i}].title' value='${book.title}'/>
<input type="hidden" name='expandableBookList[${i}]._deleted' id='expandableBookList[${i}]._deleted' value='false'/>
<span onClick="$('#expandableBookList\\[${i}\\]\\._deleted').val('true'); $('#expandableBookList${i}').hide()">Delete</span>
</div>
You don't need the
List<Book> books = new ArrayList<>()
in your domain. The hasMany will give you a books collection by default. That might be causing some issues. Also, have you debugged in your controller to make sure that the books collection is populated when the save occurs.

how to replace coding in gsp?

how to replace the coding in the finePrint?
that large textArea i call "finePrint"...
this is my problem...i am confusing..
when i filled with HMTL's coding..with ${name} on gsp..
like this..
look the arrow...thats have a button submit at below finePrint..when i click that...
the g:textField of "Your Name" thats i fill with "Bobby"..it will be replace in the finePrint with ${name}..
this ini my gsp coding where i fill it to finePrint..
<table align="center" >
<tbody>
<tr style="border-spacing:0!important;border-collapse:collapse!important;color:#666666;background-color:#F8F8F8" align="center">
<td style="padding:35px 75px 60px 75px;background-color:#fafafa;">
<table style="border-spacing:0!important;border-collapse:collapse!important;color:#666666;" width="80%">
<tbody>
<tr>
<td>
<p align="center"><img alt="Tempo AI" border="0"/></p>
<h1 style="font-family:Arial,Helvetica,sans-serif;color:#ee710b;font-size:30px;font-weight:normal;width:450px">${name}, you requested to reset your Password</h1>
<p style="padding:0;margin:0 0 15px 0;">To reset your password, just click the link below.</p>
<p style="padding:0;margin:0 0 15px 0;">Reset Password</p>
<p style="padding:0;margin:0;">Best,</p>
<p style="padding:0;margin:0;color:#bcbcbc;font-size:20px;">Tempo Team</p>
</td>
</tr>
</tbody>
</table>
</td>
</tr>
<tr style="font-family:Arial, Helvetica, sans-serif;padding-top:15px;" align="center" >
<td style="font-family:Arial, Helvetica, sans-serif;padding-top:15px;" align="center">
<p style="margin-top:0;margin-bottom:10px;">
<a href="http://www.facebook.com" style="text-decoration:none;">
<img alt="Facebook" border="0"/>
</a>
<a href="http://www.twitter.com" style="text-decoration:none;">
<img alt="Twitter" border="0"/>
</a>
<a href="http://www.plus.google.com" style="text-decoration:none;">
<img alt="Google+" border="0"/>
</a>
<a href="http://www.mail.yahoo.com" style="text-decoration:none;">
<img alt="Email" border="0"/>
</a>
</p>
<p style="margin-top:0;margin-bottom:8px;font-size:12px;font-weight:bold;">
<a style="color:#666666;text-decoration:none;">
ABOUT
</a>
<a style="color:#666666;text-decoration:none;">
PRIVACY
</a>
<a style="color:#666666;text-decoration:none;">
TERM OF USE
</a>
</p>
<p style="padding:0;margin:0;font-size:10px;color:#999999;font-weight:bold;">
If you would like to change your email notification settings
<a style="color:#44b1d9;" href="www.w3school.com">click here</a>
</p>
<p style="padding:0;margin:0;font-size:10px;color:#999999;font-weight:bold;">
© 2012 Tempo
</p>
</td>
</tr>
</tbody>
</table>
and this is my SMTP coding when i click submit..it will send email to abc#yahoo.com
def send = {
sendMail {
multipart true
to params.email
from "s_yoshitsune#yahoo.com"
subject "Test Reset Password"
html params.finePrint
}
render params.finePrint
}
and the result when i received email..
i want the ${name} replaced by my name(Bobby) where i fill before
this is coding for submit email address..
<!DOCTYPE html>
<html>
<head>
<meta name="layout" content="main"/>
<g:javascript src='jquery-1.6.2.min.js'/>
<g:javascript src='jquery.cleditor.min.js'/>
<g:javascript src='test.js'/> <%-- cara import file JavaScript/ JS --%>
<link rel="stylesheet" href="${resource(dir: 'css', file: 'cleditor/jquery.cleditor.css')}" type="text/css"> <%-- cara import file CSS --%>
<title>Reset Password</title>
</head>
<body>
<g:form action="send">
<table style="width:500px">
<tbody>
<tr>
<td>Your Email Address </td>
<%-- <td><input style="width:250px" name="email" /></td>--%>
<td><g:textField style="width:250px" name = "email"/></td>
</tr>
<tr>
<td>Your Name</td>
<td><g:textField style="width:250px" name = "user"/></td>
</tr>
<tr>
<td colspan="4">
<g:textArea name="finePrint"/>
</td>
</tr>
<tr>
<td><input type="submit"/></td>
</tr>
</tbody>
</table>
</g:form>
<div id="finePrintBlank" style="display:none;" title="${message(code: 'campaign.finePrint.label')}">
<p>${message(code: 'default.blank.message', args: [message(code: 'campaign.finePrint.label')])}</p>
</div>
</body>
</html>
In the gsp page, you can prepopulate finePrint with your html code like this,
<g:textArea name="finePrint">
<table align="center" >
<tbody>
...etc...
${name}, you requested to reset your password.
...rest of the data...
</tbody>
</table>
<g:textArea>
That will be processed on the server side and you should have your the name resolved before it reached the client.
...etc...
${domainInstance.name}, you requested to reset your password.
...rest of the data...

Knockout Validation is not working

It may be the easiest question but I am not able to resolve this. The validation on my page is not working. Everytime I am submitting the page leaving all the input fields blank, an alert is generated saying 'Failed'. And if I enter all the fields with some value data is successfully submitted.
Here is my HTML :
#{
ViewBag.Title = "Exercise10";
}
<html>
<head>
<script src="../../Scripts/jquery-1.6.2.js" type="text/javascript"></script>
<script src="../../Scripts/knockout-2.2.1.js" type="text/javascript"></script>
<script src="../../Scripts/knockout.mapping-latest.js" type="text/javascript"></script>
<script src="../../Scripts/json2.js" type="text/javascript"></script>
<link href="../../Content/ExerciseStyle.css" rel="stylesheet" type="text/css" />
<script src="../../Scripts/Popup.js" type="text/javascript"></script>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.0/themes/base/jquery- ui.css" />
<script src="http://code.jquery.com/ui/1.10.0/jquery-ui.js"></script>
<script src="../../Scripts/DatePicker.js" type="text/javascript"></script>
<script src="../../Scripts/knockout.validation.js" type="text/javascript"></script>
<script src="../../Scripts/knockout-validator.js" type="text/javascript"></script>
<script src="../../Scripts/knockout-validator-extensions.js" type="text/javascript"></script>
<link href="../../Scripts/extensions.css" rel="stylesheet" type="text/css" />
</head>
<body>
<form action="" method="post">
<div id="MainArea">
<table id="tbllist" align="center" style="margin-left: 15px; width: 96%; margin- right: 15px;">
<tr>
<th colspan="3" align="left">
<div id="title_p">
Enter Following Entries</div>
</th>
</tr>
<tr>
<td align="right" style="width: 40%;">
<b>Name :</b>
</td>
<td align="left" style="width: 17%;">
<input data-bind="value: EmployeeName" placeholder="Employee Name" class="txt"
type="text" />
</td>
<td align="left">
</td>
</tr>
<tr>
<td align="right">
<b>Emp# :</b>
</td>
<td align="left">
<input data-bind="value: EmployeeCode" placeholder="Employee Code" style="width: 200px;"
type="text" />
</td>
<td align="left">
</td>
</tr>
<tr>
<td align="right">
<b>Date of Birth :</b>
</td>
<td align="left">
<input data-bind="value: Dob" id="datepicker" placeholder="Date of Birth" style="width: 200px;"
type="text" /><span>(dd/mm/yyyy)</span>
</td>
<td align="left">
</td>
</tr>
<tr>
<td align="right">
<b>Age (18-60):</b>
</td>
<td align="left">
<input data-bind="value: Age" style="width: 200px;" placeholder="Age Range (18-60)"
type="number" min="18" max="60" />
</td>
<td align="left">
</td>
</tr>
<tr>
<td align="right">
<b>Contact Number :</b>
</td>
<td align="left">
<input data-bind="value: ContactNumber" placeholder="Contact Number" style="width: 200px;"
type="text" />
</td>
<td align="left">
</td>
</tr>
<tr>
<td align="right">
<b>Email :</b>
</td>
<td align="left">
<input data-bind="value: EmailID" placeholder="Email ID" style="width: 200px;"
type="email" />
</td>
<td align="left">
</td>
</tr>
<tr>
<td align="right">
<b>Address :</b>
</td>
<td align="left">
<input data-bind="value: Address" placeholder="Address" style="width: 200px;"
type="text" />
</td>
<td align="left">
</td>
</tr>
<tr>
<td align="right">
<b>City :</b>
</td>
<td align="left">
<select data-bind="value: City" style="width: 200px;">
<option value="Noida">New Delhi</option>
<option value="Noida">Noida</option>
<option value="Noida">Mumbai</option>
</select>
</td>
<td align="left">
</td>
</tr>
<tr>
<td align="right">
<b>Marital Status :</b>
</td>
<td align="left">
<input data-bind="checked: MaritalStatus" checked="checked" name="rdb" type="radio" /><span>UnMarried</span>
<input data-bind="checked: MaritalStatus" checked="checked" name="rdb" type="radio" checked="checked" /><span>Married</span>
</td>
<td align="left">
</td>
</tr>
<tr>
<td align="right">
<b>Any Employee Reference :</b>
</td>
<td align="left">
<input data-bind="checked: Is_Reference" type="checkbox" />yes
</td>
<td align="left">
</td>
</tr>
</table>
<table style="width: 99%; margin-right: 20px; padding: 5px;">
<tr align="right">
<td>
<button data-bind="click :$root.save" class="button">Save</button>
<input type="button" id="btnCancel" class="button" value="Cancel" onclick="JavaScript:closePopup();" />
</td>
</tr>
</table>
</div>
</form>
And My View Model (continued from the above):
<script type="text/javascript">
//....................................................//
var EmpViewModel = function () {
//Make the self as 'this' reference
var self = this;
//Declare observable which will be bind with UI
self.EmployeeCode = ko.observable("").extend({ required: true });
self.EmployeeName = ko.observable("").extend({ required: { message: 'Please supply your Name.'} });
self.Dob = ko.observable("");
self.Age = ko.observable("").extend({number :true});
self.ContactNumber = ko.observable("");
self.EmailID = ko.observable("");
self.Address = ko.observable("");
self.MaritalStatus = ko.observable("");
self.City = ko.observable("");
self.Is_Reference = ko.observable("");
//The Object which stored data entered in the observables
var EmpData = {
EmpCode: self.EmployeeCode,
EmpName: self.EmployeeName,
Dob: self.Dob,
Age: self.Age,
ContactNumber: self.ContactNumber,
MaritalStatus: self.MaritalStatus,
EmailID: self.EmailID,
Address: self.Address,
City: self.City,
Is_Reference: self.Is_Reference
};
//Declare an ObservableArray for Storing the JSON Response
self.Employees = ko.observableArray([]);
//Function to perform POST (insert Employee) operation
self.save = function () {
//Ajax call to Insert the Employee
$.ajax({
type: "POST",
url: "/Exercise/Save/",
data: ko.toJSON(this), //Convert the Observable Data into JSON
contentType: "application/json",
success: function (data) {
alert(data);
},
error: function () {
alert("Failed");
}
});
//Ends Here
};
}
ko.applyBindings(new EmpViewModel());
</script>
Knockout-validation shows validation messages only if the fields are modified. Therefore you should check on submit if all fields are valid and show all errors if not.
self.errors = ko.validation.group(this, { deep: true, observable: false });
//Function to perform POST (insert Employee) operation
self.save = function () {
// check if valid
if(self.errors().length > 0) {
self.errors.showAllMessages();
return;
}
//Ajax call to Insert the Employee
$.ajax({
type: "POST",
url: "/Exercise/Save/",
data: ko.toJSON(this), //Convert the Observable Data into JSON
contentType: "application/json",
success: function (data) {
alert(data);
},
error: function () {
alert("Failed");
}
});
//Ends Here
};
I have created a fiddle to show that: http://jsfiddle.net/delixfe/tSzYf/2/

Display of image in show page

I have option of photo upload in my create.gsp page. I'm able to see the uploaded photo in my create page and able to upload my photo in database, but cannot see that photo in my show page.
This is create.gsp page
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta name="layout" content="billing-without-grid" />
<g:set var="entityName"
value="${message(code: 'skeletonBill.label', default: 'SkeletonBill')}" />
<title><g:message code="default.create.label"
args="[entityName]" /></title>
<script>
function showPhoto(imageFile) {
var fileReader = new FileReader();
var image = document.getElementById("uploadPhotoFile");
fileReader.onload = function(e) {
image.src = e.target.result;
}
fileReader.readAsDataURL(imageFile.files[0]);
}
</script>
</head>
<body>
<div class="body">
<div class="container-fluid">
<div class="row">
<div class="span6">
<img src="" name="uploadPhotoFile" id="uploadPhotoFile"
height="200" width="160" />
<table style="width: 25%">
<tbody>
<tr class="prop">
<td valign="top" class="name"><label for="uploadPhoto"><g:message code="uploadInformation.uploadPhoto.label" default="Upload Photo" /></label></td>
<td valign="top" class="value ${hasErrors(bean: uploadInformationInstance, field: 'uploadPhoto', 'errors')}">
<input type="file" id="uploadPhoto" name="uploadPhoto" onchange="showPhoto(this)" />
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
</body>
</html> '
Domain class that I created
class UploadInformation {
static constraints = {
uploadPhoto(nullable:true, maxSize: 16384 /* 16K */)
}
byte[] uploadPhoto
static transients = ["uploadPhoto"]
static mapping = {
uploadPhoto column:"uploadPhoto",sqlType: "blob"
}
}
Anuj.
The problem I see after quick look at your code is:
static transients = ["uploadPhoto"]
UploadPhoto will not be saved to database because it's declarated as transient.
See more details transient properties

Grails upload image

I am trying to upload a picture, and save it in database.
If I do the following I get this error:
Failed to convert property value of type
org.springframework.web.multipart.commons.CommonsMultipartFile to
required type java.lang.Byte[] for property picture1; nested exception
is java.lang.IllegalArgumentException: Cannot convert value of type
[org.springframework.web.multipart.commons.CommonsMultipartFile] to
required type [java.lang.Byte] for property picture1[0]:
PropertyEditor
[org.springframework.beans.propertyeditors.CustomNumberEditor]
returned inappropriate value
If i do it this way:
if(request instanceof MultipartHttpServletRequest){
MultipartHttpServletRequest mpr = (MultipartHttpServletRequest)request;
CommonsMultipartFile f = (CommonsMultipartFile) mpr.getFile("picture1");
}
I get this error:
Executing action [save] of controller [com.testapp.RequestController]
caused exception: Cannot cast object '
org.springframework.web.multipart.commons.CommonsMultipartFile#34ae1f02'
with class
'org.springframework.web.multipart.commons.CommonsMultipartFile' to
class 'java.lang.Byte'
What should I do to make this work?
Domain
package com.testapp
class Request{
String requestID
Date dateCreated
String subject
String startedBy
String description
String status
String priority
Productline productline
Topic topic
Subtopic subtopic
String company
Byte [] picture1
Byte [] picture2
Byte [] picture3
String acceptedBy
static constraints = {
requestID(blank:true,nullable:true)
dateCreated(blank:true,nullable:true)
subject()
description(maxSize:5000)
status (blank:true,nullable:true)
priority(inList:["Normal","Urgent","Not urgent"])
productline(blank:true,nullable:true)
topic(blank:true,nullable:true)
subtopic(blank:true,nullable:true)
company(blank:true,nullable:true)
startedBy(blank:true,nullable:true)
acceptedBy(blank:true,nullable:true)
picture1(blank:true,nullable:true)
picture2(blank:true,nullable:true)
picture3(blank:true,nullable:true)
}
}
GSP:
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta name="layout" content="main" />
<g:set var="entityName" value="${message(code: 'request.label', default: 'Request')}" />
<title><g:message code="New request" args="[entityName]" /></title>
</head>
<body>
<div class="nav">
<span class="menuButton"><a class="home" href="${createLink(uri: '/')}"><g:message `code="default.home.label"/></a></span>`
<span class="menuButton"><g:link class="list" action="userList"><g:message code="Lista zahteva" `args="[entityName]" /></g:link></span>`
</div>
<div class="body">
<h1><g:message code="New request" args="[entityName]" /></h1>
<g:if test="${flash.message}">
<div class="message">${flash.message}</div>
</g:if>
<g:hasErrors bean="${requestInstance}">
<div class="errors">
<g:renderErrors bean="${requestInstance}" as="list" />
</div>
</g:hasErrors>
<g:form action="save" method="post" enctype="multipart/form-data">
<div class="dialog">
<table>
<tbody>
<tr class="prop">
<td valign="top" class="name">
<label for="subject"><g:message code="request.subject.label" default="Subject" /></label>
</td>
<td valign="top" class="value ${hasErrors(bean: requestInstance, field: 'subject', 'errors')}">
<g:textField name="subject" value="${requestInstance?.subject}" />
</td>
</tr>
<tr class="prop">
<td valign="top" class="name">
<label for="description"><g:message code="request.description.label" default="Opis" /></label>
</td>
<td valign="top" class="value ${hasErrors(bean: requestInstance, field: 'description', 'errors')}">
<g:textArea name="description" cols="40" rows="5" value="${requestInstance?.description}" />
</td>
</tr>
<tr>
<td valign="top" class="name">
<label for="picture1"><g:message code="request.picture1.label" default="Printscreen" /></label>
</td>
<td valign="top" class="value">
<input type="file" id="picture1" name="picture1"/>
</td>
</tr>
<tr class="prop">
<td valign="top" class="name">
<label for="priority"><g:message code="request.priority.label" default="Priority" /></label>
</td>
<td valign="top" class="value ${hasErrors(bean: requestInstance, field: 'status', 'errors')}">
<g:select name="priority" from="${requestInstance.constraints.priority.inList}" value="${requestInstance?.priority}" valueMessagePrefix="request.priority" />
</td>
</tr>
<tr class="prop">
<td valign="top" class="name">
<label for="productline"><g:message code="request.productline.label" default="Productline" /></label>
</td>
<td valign="top" class="value ${hasErrors(bean: requestInstance, field: 'productline', 'errors')}">
<g:select name="productline.id" from="${com.testapp.Productline.list()}" optionKey="id" value="${requestInstance?.productline?.id}" />
</td>
</tr>
<tr class="prop">
<td valign="top" class="name">
<label for="topic"><g:message code="request.topic.label" default="Topic" /></label>
</td>
<td valign="top" class="value ${hasErrors(bean: requestInstance, field: 'topic', 'errors')}">
<g:select name="topic.id" from="${com.testapp.Topic.list()}" optionKey="id" value="${requestInstance?.topic?.id}" />
</td>
</tr>
<tr class="prop">
<td valign="top" class="name">
<label for="subtopic"><g:message code="request.subtopic.label" default="Subtopic" /></label>
</td>
<td valign="top" class="value ${hasErrors(bean: requestInstance, field: 'subtopic', 'errors')}">
<g:select name="subtopic.id" from="${com.testapp.Subtopic.list()}" optionKey="id" value="${requestInstance?.subtopic?.id}" />
</td>
</tr>
</tbody>
</table>
</div>
<div class="buttons">
<span class="button"><g:submitButton name="create" class="save" value="${message(code: 'default.button.create.label', default: 'Create')}" /></span>
</div>
</g:form>
</div>
</body>
Controller:
def save = {
def requestInstance = new Request(params)
def requestNumberInstance = new RequestNumber()
def upPic1 = request.getFile('picture1')
def lastReqNum = RequestNumber.find("from RequestNumber ORDER BY requestNumber desc")
if(lastReqNum){
requestNumberInstance.requestNumber = lastReqNum.requestNumber + 1
}
else{
requestNumberInstance.requestNumber = 110000
}
requestInstance.requestID = "CSC" + requestNumberInstance.requestNumber
def currentUserContact = Contact.findByUser(springSecurityService.getCurrentUser())
requestInstance.startedBy = currentUserContact.realname
requestInstance.company = currentUserContact.company
requestInstance.status = "Opened"
requestInstance.acceptedBy = "Not yet accepted"
requestInstance.picture1 = upPic1
if(requestNumberInstance.save()){
if (requestInstance.save()) {
flash.message = "${message(code: 'default.created.message', args: [message(code: 'request.label', default: 'Request'), requestInstance.id])}"
redirect(action: "show", id: requestInstance.id)
}
else {
render(view: "create", model: [requestInstance: requestInstance])
}
}
else{
render(view: "create", model: [requestInstance: requestInstance])
}
}
Please dont mind the spaghetti code. I'm just trying to get some basic concepts. I will clear it later.
Simplified example:
def save = {
def requestInstance = new Request(params)
def requestNumberInstance = new RequestNumber()
if(requestInstance.validate() && requestInstance.save(flush: true)){
println "Saved successfully with ${requestInstance.picture1.length} bytes"
}
else {
println "Save failed"
}
Update after question edit
The error is probably caused by this:
def upPic1 = request.getFile('picture1')
...
requestInstance.picture1 = upPic1
request.getFile() is returning a MultipartFile, and you're trying to assign it to a Byte[] field. Considering my small example (below), you shouldn't even need to try to make this assignment. The def requestInstance = new Request(params) will bind the byte[] automatically.
Uploaded files bind automatically to byte[] fields. Here's a working example:
Domain: grails-app/domain/my/Example.groovy
package my
class Example {
byte[] file
}
Controller: grails-app/controllers/my/ExampleController.groovy
package my
class ExampleController {
def create = { }
def save = {
def example = new Example(params)
if(example.validate() && example.save(flush: true)) {
println "Saved successfully with ${example.file.length} bytes"
} else {
println "Save failed"
}
redirect(action: 'create')
}
}
GSP: grails-app/views/example/create.gsp
<!DOCTYPE html>
<html>
<body>
<g:uploadForm action="save">
<input type="file" name="file"/>
<g:submitButton name="submit"/>
</g:uploadForm>
</body>
</html>
When I upload a small file using the GSP form, I see the following console output:
Saved successfully with 23 bytes
Suggestions
Try using Grails data binding to save your file contents.
Make sure your form is a <g:uploadForm> or has an enctype="multipart/form-data" if you're using a vanilla`.
Make sure you're binding the params using the domain constructor, domain.properties, or bindData().
I am guessing your typing is messed up.
What happens if you simply do:
def f = request.getFile('myFile')
as described in the manual. If you want strong typing it should be MultiPartfile, not CommonsMultiPartFile, as far as I remember (and you get it right from the request object).
This is the interface you're working on: http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/web/multipart/MultipartFile.html
The relevant method for you, should be getBytes().
Edit for edited question:
As I said, you want getBytes(), you are trying to shove a MultiPartFile into a byte array, thats not going to work.
requestInstance.picture = upPic.getBytes() and you should be allright.
It only worked when I changed my domain properties picture1,picture2,picture3 to:
byte [] picture1
byte [] picture2
byte [] picture3
and added those mappings:
static mapping = {
picture1 column:"picture1", sqlType: "blob"
picture2 column:"picture2", sqlType: "blob"
picture3 column:"picture3", sqlType: "blob"
}

Resources