Attachments

Framework Core
Tag Helper <attachments>

Functionality for uploading and displaying attachments or files.

Attributes

<attachments>

Properties

bool readOnly
Default: false

Make the control read only.

string buttonText
Default: Add Attachment

The text on the upload button.

bool hoverResize
Default: true

Cause preview images to go full size when hovered over.

string imagePageFunction

Javascript function to call which is passed the current URL and will return the updated URL.

bool showUploadTime
Default: false

Will show the upload time under the filename. The Attachment model has an UploadTime string field which takes precedence but if empty then UploadTimeUtc and TimezoneId are used to format the time.

bool showPreview
Default: true

Show the preview pane when hovering over images.

string multipleUpload
Default: true

Allow multiple files to be uploaded at a time.

string group

Sets the group that these attachments are allocated to. When set, all the files from a particular location are loaded at once to improve performance, and the group or category is used to differentiate them to different attachment controls. Allocating groups can speed up the loading of files if they all come from the same source as only a single call is required to retrieve rather than a call for each attachment control.

Javascript

ShareItLibrary.Attachment.Render({
data: {
myId: $('#MyId').val()
},
renderUrl: '/Controller/Attachments',
imagePage: '/Controller/Thumbnail',
downloadUrl: '/Controller/Download',
uploadUrl: '/Controller/UploadFiles',
deleteUrl: '/Controller/DeleteFile',
callBack: function (d) {
$('#' + d.id).length;
}
});

This example passes through the Id of the attachment to target, and provides an optional renderFunction if the parent element contains data-custom-render

ShareItLibrary.Attachment.Render({
id: o.data('my-id'),
data: {
myId: $('#MyId').val()
},
renderUrl: '/Controller/Attachments',
downloadUrl: '/Controller/Download',
uploadUrl: '/Controller/UploadFiles',
deleteUrl: '/Controller/DeleteFile',
renderFunction: typeof o.parent().data('custom-render') !== 'undefined' ? MyJavascriptNamespace.MyJsFile.AttachmentRender : (function () { return; })()
});

Properties

id

Optional id to target. If not provided defaults to FileUploadBox.

data

The JSON data structure to send with requests. This can contain parent ids etc. to be received by the controller on upload or render.

renderUrl

The url that returns the list of files.

imagePage

URL to download the thumbnail files. This can be the same as the downloadUrl.

downloadUrl

URL to download the file.

uploadUrl

URL to upload the file.

deleteUrl

URL to delete the file.

renderFunction

The function called for a custom render.

dropFunction

The function called when a drop is made and before uploading begins.

callBack

Function to call when rendering is complete.

Javascript

event loaded

Tiggered when the attachments are rendered.

data loaded

Is defined after an attachment field has rendered. Is undefined when rendering. $('#AttachmentId').data('loaded') !== undefined

Javascript Functions

ShareItLibrary.Attachment.ModifyFormField(property, value, id)

Changes a field being posted back with upload etc after the Render has been initialised. This allows changing fields to be sent back with file uploads and renders etc.

ShareItLibrary.Attachment.ModifyFormField('field', $('#Field').val(), o.data('id')
ShareItLibrary.Attachment.InitFileUpload (uploadUrl, renderFunction, id, customRender = false, dropFn = null);

Properties

uploadUrl

The C# function which will upload the files.

renderFunction

The javascript function to render files.

id

The unique id for this upload box.

customRender

If true then do not make the upload buttons visible again automatically after upload. The renderFunction will need to do this.

dropFn

Supply a function to call after the files are dropped on the drop box but before the upload begins.

ShareItLibrary.Attachment.RenderAttachments (attachments, imagePage, downloadFunction, deleteFunction, id);

Properties

attachments

The json data which holds the list of attachments.

imagePage

The C# function to render the image.

downloadFunction

The javascript function to download files.

deleteFunction

The javascript function to delete files.

id
Default: FileUploadBox

The id of the upload box.

Allow uploading, deleting of files.

Razor
<attachments read-only="@readOnly"></attachments>
Javascript

On Init

if ($('#FileUploadBox').length) {
ShareItLibrary.Attachment.InitFileUpload('/Ajax/UploadFiles', MyApp.Controller.RenderFiles);
}
C#
[HttpGet]
public ActionResult Download(Guid aid)
{
var Attachment = db.AttachmentGet(aid, null, null, User.UserId()).SingleOrDefault();

if (Attachment != null)
return File(Attachment.Attachment, SiUtil.ContentTypeFromFilename(Attachment.Filename), Attachment.Filename);
else
return null;
}

[HttpPost]
public ActionResult DeleteFile(Guid aid)
{
var Attachment = db.AttachmentDelete(aid, User.UserId());

return Json("");
}

[HttpPost]
public JsonResult Attachments(Guid? issueId, Guid? discussionId)
{
var attachments = db.AttachmentGet(null, issueId, discussionId, User.UserId()).ToList();

return Json(attachments);
}

Allow uploading, deleting of single file.

Razor
<attachments></attachments>
Javascript

On Init

MyApp.JsController.Init = function () {
ShareItLibrary.Attachment.AddFormData("FileId", $('#FileId').val());
ShareItLibrary.Attachment.InitFileUpload('UploadFiles', MyApp.JsController.RenderFiles);
MyApp.JsController.RenderFiles();
};

MyApp.JsController.DownloadFile = function (fileId) {
window.open('Download?aid=' + fileId);
};

MyApp.JsController.RenderFiles = function () {
var headers = {};
headers['__RequestVerificationToken'] = $('[name="__RequestVerificationToken"]').val();

$.ajax({
type: "POST",
url: '/Controller/Files',
headers: headers,
data: 'FileId=' + $('#FileId').val(),
dataType: "json",
error: function (jqXHR, textStatus, errorThrown) {
alert(errorThrown);
}
}).done(function (data) {
ShareItLibrary.Attachment.RenderAttachments(data, 'Download', 'MyApp.JsController.DownloadFile', 'MyApp.JsController.DeleteFile');
});
};
C#
[HttpPost]
public ActionResult EditSet(FileGet_Result file)
{
if (ModelState.IsValid)
{
db.FileSet(file.FileId, file.FileType, null, null);
...
}
}

[HttpPost]
public ActionResult Files(Guid? fileId)
{
var files = db.FileGet(fileId, null).Select(f => new { Filename = f.FileName, AttachmentId = f.FileId }).ToList();

return Json(files);
}

[HttpGet]
public ActionResult Download(Guid aid)
{
var file = db.FileGet(aid, null).SingleOrDefault();

if (file != null)
return File(file.FileData, SiUtil.ContentTypeFromFilename(file.FileName), file.Filename);
else
return null;
}

[HttpPost]
public JsonResult UploadFiles(Guid? fileId)
{
var files = Request.Files;
foreach (string key in files)
{
var file = files[key];
string filename = file.FileName.Substring(file.FileName.LastIndexOf('\\') + 1);

byte[] fileData = new byte[file.InputStream.Length];
file.InputStream.Read(fileData, 0, fileData.Length);

db.FileSet(fileId, null, filename, fileData);
}

return Json("");
}

Upload Only with Pre Drop check

Razor
<attachments button-text="Upload"></attachments>
Javascript

On Init

if ($('#FileUploadBox').length) {
ShareItLibrary.Attachment.InitFileUpload('/Controller/UploadFiles', function (d) {
if (d.Total > 0) {
$('#BulkUpload').val('True');
$('#BulkUpload').closest('form').submit();
}
else
window.location.reload();
}, undefined, undefined, function() {
... do something
});
}
C#
[HttpGet]
public JsonResult UploadFiles()
{
var files = Request.Files;

foreach (string key in files)
ImportFile(files[key]);

return Json("");
}

private void ImportFile(HttpPostedFileBase file)
{
StreamReader csvreader = new StreamReader(file.InputStream);

CsvHelper.CsvReader csv = new CsvHelper.CsvReader(csvreader);

var records = csv.GetRecords<MyCsv>().ToList();

... do stuff with records.
}

ImagePageFunction

Razor
<attachments attachments="ViewBag.Attachments" download-function="MyApp.Controller.DownloadFile" image-page="/Controller/Action" image-page-function="MyApp.Controller.ImagePageFunction"></attachments>
Javascript
MyApp.Controller.ImagePageFunction = function (url) {
return url + "&prop=test";
}