This is from a small, scratch application where the Center has many StubFile (which has an ERAttachment named fileAttachment)
public WOActionResults fileUploadAction() {
WOResponse res = new WOResponse();
if (!this.request().formValues().containsKey("centerkey") || !this.request().formValues().containsKey("fileToBeUploaded")) {
res.setStatus(400);
res.appendContentString("<html><head><title>ERROR</title></head><body><h1>Missing Parameters</h1></body></html");
return res;
}
Integer ck = new Integer(this.request().formValueForKey("centerkey").toString());
logger.debug("looking for center with key " + ck);
WOInputStreamData wois = (WOInputStreamData) this.request().formValueForKey("fileToBeUploaded");
String mimeType = (String) this.request().formValueForKey("mimetype");
EOEditingContext ec = ERXEC.newEditingContext();
Center c = (Center) EOUtilities.objectWithPrimaryKeyValue(ec, Center.ENTITY_NAME, ck);
logger.debug("found " + c.name() + " for centerkey " + ck);
StubFile f = (StubFile) EOUtilities.createAndInsertInstance(ec, StubFile.ENTITY_NAME);
f.setCenterId(ck);
f.setCenterRelationship(c);
f.setFilename((String) this.request().formValueForKey("filename"));
f.setTitle((String) this.request().formValueForKey("title"));
try {
NSData fileData = new NSData(wois.bytes());
File up;
up = File.createTempFile("curlupload", "vaws");
FileOutputStream uploadingFile = new FileOutputStream(up);
fileData.writeToStream(uploadingFile);
uploadingFile.close();
ERAttachment attachment = ERAttachmentProcessor.processorForType("file").process(ec, up, null, mimeType, "StubFile.fileAttachment", null);
f.setFileAttachmentRelationship(attachment);
ec.saveChanges();
} catch (IOException e) {
e.printStackTrace();
res.setStatus(501);
res.appendContentString("<html><head><title>ERROR</title></head><body><h1>File Error:</h1><pre>" + e.getMessage() + "</pre></body></html");
return res;
}
res.setStatus(201);
res.appendContentString("<html><head><title>Success</title></head><body><h1>attachment loaded</h1></body></html");
return res;
}