Asp.net File Upload Control - asp.net

I Had a file upload control I want that file will attach only when it is below under some Memory Limit (8 Mb). I get the file size using Ajax and call it on the onchange event. But I am not able to restrict the attachment of files. Can any one Help me ?
This is the example code
function a(obj) {
if ($(obj).val() != '') {
var request;
var flag = false;
request = $.ajax({
type: "POST",
url: 'CheckFileSize.aspx',
data: "search=" + $(obj).val(),
success: function (size) {
if (parseFloat(size) < 8192) {
flag = true;
}
if (!flag) {
alert('File size is greater then 8 MB. The size of the file is ' + (parseFloat(size)) / 1024 + ' MB');
//Doing something that restrict user from upload enter code here
$(obj).val(null);
}
return flag;
}
});
}
return false;
}

In your server-side method where you process the uploaded file, add this code:
if (myFileUploadControl.HasFile)
{
int maxSize = Convert.ToInt32(ConfigurationManager.AppSettings.Get("MaxImageSize")); //MaxImageSize specified in web.config file to make it easy to change.
int imageSize = myFileUploadControl.PostedFile.ContentLength;
if (imageSize > maxSize)
{
string uploadImageError = "The selected file exceeds the maximum allowed size (" + maxSize / 1000 + "k)"; // Message to display to user.
}
else
{
// Code to process the file here.
}
}
Adding the following to the system.web section of the web.config file will also prevent over-large uploads from being accepted.
<!-- set max upload to 25 MB -->
<httpRuntime executionTimeout="300" maxRequestLength="25000"/>

You should be able to clear the value of the input - in jQuery it would look something like
$('#fileInputId').val('')

Related

CKFinder3 ASP.NET The file browser is disabled for security reasons

I know this question is already answered but that's for PHP user. I'm using ASP.NET and this error keep happens. I tried to look for the config in the CKFinderScripts folder but there is no such config (in 2nd version there is but i dont understand why this version is not). I created a config in aspx myself but it still doesn't work.
<%# Control Language="C#" EnableViewState="false" AutoEventWireup="false" Inherits="CKFinder.Settings.ConfigFile" %>
<%# Import Namespace="CKFinder.Settings" %>
<script runat="server">
/**
* This function must check the user session to be sure that he/she is
* authorized to upload and access files using CKFinder.
*/
public override bool CheckAuthentication()
{
// WARNING : DO NOT simply return "true". By doing so, you are allowing
// "anyone" to upload and list the files in your server. You must implement
// some kind of session validation here. Even something very simple as...
//
// return ( Session[ "IsAuthorized" ] != null && (bool)Session[ "IsAuthorized" ] == true );
//
// ... where Session[ "IsAuthorized" ] is set to "true" as soon as the
// user logs on your system.
return true;
}
/**
* All configuration settings must be defined here.
*/
public override void SetConfig()
{
// Paste your license name and key here. If left blank, CKFinder will
// be fully functional, in Demo Mode.
LicenseName = "";
LicenseKey = "";
// The base URL used to reach files in CKFinder through the browser.
BaseUrl = "/ckfinder/userfiles/";
// The phisical directory in the server where the file will end up. If
// blank, CKFinder attempts to resolve BaseUrl.
BaseDir = "";
// Optional: enable extra plugins (remember to copy .dll files first).
Plugins = new string[] {
// "CKFinder.Plugins.FileEditor, CKFinder_FileEditor",
// "CKFinder.Plugins.ImageResize, CKFinder_ImageResize",
// "CKFinder.Plugins.Watermark, CKFinder_Watermark"
};
// Settings for extra plugins.
PluginSettings = new Hashtable();
PluginSettings.Add("ImageResize_smallThumb", "90x90" );
PluginSettings.Add("ImageResize_mediumThumb", "120x120" );
PluginSettings.Add("ImageResize_largeThumb", "180x180" );
// Name of the watermark image in plugins/watermark folder
PluginSettings.Add("Watermark_source", "logo.gif" );
PluginSettings.Add("Watermark_marginRight", "5" );
PluginSettings.Add("Watermark_marginBottom", "5" );
PluginSettings.Add("Watermark_quality", "90" );
PluginSettings.Add("Watermark_transparency", "80" );
// Thumbnail settings.
// "Url" is used to reach the thumbnails with the browser, while "Dir"
// points to the physical location of the thumbnail files in the server.
Thumbnails.Url = BaseUrl + "_thumbs/";
if ( BaseDir != "" ) {
Thumbnails.Dir = BaseDir + "_thumbs/";
}
Thumbnails.Enabled = true;
Thumbnails.DirectAccess = false;
Thumbnails.MaxWidth = 100;
Thumbnails.MaxHeight = 100;
Thumbnails.Quality = 80;
// Set the maximum size of uploaded images. If an uploaded image is
// larger, it gets scaled down proportionally. Set to 0 to disable this
// feature.
Images.MaxWidth = 1600;
Images.MaxHeight = 1200;
Images.Quality = 80;
// Indicates that the file size (MaxSize) for images must be checked only
// after scaling them. Otherwise, it is checked right after uploading.
CheckSizeAfterScaling = true;
// Increases the security on an IIS web server.
// If enabled, CKFinder will disallow creating folders and uploading files whose names contain characters
// that are not safe under an IIS 6.0 web server.
DisallowUnsafeCharacters = true;
// If CheckDoubleExtension is enabled, each part of the file name after a dot is
// checked, not only the last part. In this way, uploading foo.php.rar would be
// denied, because "php" is on the denied extensions list.
// This option is used only if ForceSingleExtension is set to false.
CheckDoubleExtension = true;
// Due to security issues with Apache modules, it is recommended to leave the
// following setting enabled. It can be safely disabled on IIS.
ForceSingleExtension = true;
// For security, HTML is allowed in the first Kb of data for files having the
// following extensions only.
HtmlExtensions = new string[] { "html", "htm", "xml", "js" };
// Folders to not display in CKFinder, no matter their location. No
// paths are accepted, only the folder name.
// The * and ? wildcards are accepted.
// By default folders starting with a dot character are disallowed.
HideFolders = new string[] { ".*", "CVS" };
// Files to not display in CKFinder, no matter their location. No
// paths are accepted, only the file name, including extension.
// The * and ? wildcards are accepted.
HideFiles = new string[] { ".*" };
// Perform additional checks for image files.
SecureImageUploads = true;
// Enables protection in the connector.
// The default CSRF protection mechanism is based on double submit cookies, where
// connector checks if the request contains a valid token that matches the token
// sent in the cookie
//
// https://www.owasp.org/index.php/Cross-Site_Request_Forgery_%28CSRF%29_Prevention_Cheat_Sheet#Double_Submit_Cookies
EnableCsrfProtection = true;
// The session variable name that CKFinder must use to retrieve the
// "role" of the current user. The "role" is optional and can be used
// in the "AccessControl" settings (bellow in this file).
RoleSessionVar = "CKFinder_UserRole";
// ACL (Access Control) settings. Used to restrict access or features
// to specific folders.
// Several "AccessControl.Add()" calls can be made, which return a
// single ACL setting object to be configured. All properties settings
// are optional in that object.
// Subfolders inherit their default settings from their parents' definitions.
//
// - The "Role" property accepts the special "*" value, which means
// "everybody".
// - The "ResourceType" attribute accepts the special value "*", which
// means "all resource types".
AccessControl acl = AccessControl.Add();
acl.Role = "*";
acl.ResourceType = "*";
acl.Folder = "/";
acl.FolderView = true;
acl.FolderCreate = true;
acl.FolderRename = true;
acl.FolderDelete = true;
acl.FileView = true;
acl.FileUpload = true;
acl.FileRename = true;
acl.FileDelete = true;
// Resource Type settings.
// A resource type is nothing more than a way to group files under
// different paths, each one having different configuration settings.
// Each resource type name must be unique.
// When loading CKFinder, the "type" querystring parameter can be used
// to display a specific type only. If "type" is omitted in the URL,
// the "DefaultResourceTypes" settings is used (may contain the
// resource type names separated by a comma). If left empty, all types
// are loaded.
// ==============================================================================
// ATTENTION: Flash files with `swf' extension, just like HTML files, can be used
// to execute JavaScript code and to e.g. perform an XSS attack. Grant permission
// to upload `.swf` files only if you understand and can accept this risk.
// ==============================================================================
DefaultResourceTypes = "";
ResourceType type;
type = ResourceType.Add( "Files" );
type.Url = BaseUrl + "files/";
type.Dir = BaseDir == "" ? "" : BaseDir + "files/";
type.MaxSize = 0;
type.AllowedExtensions = new string[] { "7z", "aiff", "asf", "avi", "bmp", "csv", "doc", "docx", "fla", "flv", "gif", "gz", "gzip", "jpeg", "jpg", "mid", "mov", "mp3", "mp4", "mpc", "mpeg", "mpg", "ods", "odt", "pdf", "png", "ppt", "pptx", "pxd", "qt", "ram", "rar", "rm", "rmi", "rmvb", "rtf", "sdc", "sitd", "swf", "sxc", "sxw", "tar", "tgz", "tif", "tiff", "txt", "vsd", "wav", "wma", "wmv", "xls", "xlsx", "zip" };
type.DeniedExtensions = new string[] { };
type = ResourceType.Add( "Images" );
type.Url = BaseUrl + "images/";
type.Dir = BaseDir == "" ? "" : BaseDir + "images/";
type.MaxSize = 0;
type.AllowedExtensions = new string[] { "bmp", "gif", "jpeg", "jpg", "png" };
type.DeniedExtensions = new string[] { };
type = ResourceType.Add( "Flash" );
type.Url = BaseUrl + "flash/";
type.Dir = BaseDir == "" ? "" : BaseDir + "flash/";
type.MaxSize = 0;
type.AllowedExtensions = new string[] { "swf", "flv" };
type.DeniedExtensions = new string[] { };
}
</script>
CKFinder 3 doesn't use config.aspx. It uses web.config. Now, if you are using CKFinder as standalone application then please see: https://docs.ckeditor.com/ckfinder/ckfinder3-net/quickstart.html#quickstart_configuration_authentication. Adding the * in <add key="ckfinderAllowedRole" value="" /> will fix the problem but please note that everyone will have access to your CKFinder then and while this approach may be good for testing, you should create your own authentication mechanism before hitting the production: https://docs.ckeditor.com/ckfinder/ckfinder3-net/howto.html#howto_custom_authenticator
If your CKFinder is integrated into application e.g. you have used basic MVC template together with NuGet packages then it is the application which controls access to its resources and in order to get to CKFinder, you need to log into your application (simple as that). If you have any extra access levels where you can define what user can access or not, this is something, you figure out and configure on your own.

Progressive Upload and Encryption with CryptoJS

The goal here is to upload a file, encrypt it at the client side, and send the file and its attributes via AJAX to myphpscript.php. To allow larger files, I want to upload in slices using the FileReader slice method and progressively encrypt the slices using the methods described on the CryptoJS site (https://code.google.com/p/crypto-js/). My code below runs, but only ends up storing a a small portion of the intended entire encrypted file. Can I progressively upload and encrypt in the way I am describing?
<script type="text/javascript" src="js/jquery-1.11.0.min.js"></script>
<script src="js/aes.js"></script>
<script>
function readBlob(opt_startByte, opt_stopByte) {
var files = document.getElementById('fileinput').files;
if (!files.length) {
alert('Please select a file!');
return;
}
var file = files[0];
var start = parseInt(opt_startByte) || 0;
var stop = parseInt(opt_stopByte) || file.size - 1;
var reader = new FileReader();
// If we use onloadend, we need to check the readyState.
reader.onloadend = function(evt) {
if (evt.target.readyState == FileReader.DONE) { // DONE == 2
window.bits.push(aesEncryptor.process(evt.target.result));
}
};
var blob = file.slice(start, stop + 1);
reader.readAsBinaryString(blob);
}
function handling(evt) {
// INITIALIZE PROGRESSIVE ENCRYPTION
var key = CryptoJS.enc.Hex.parse(document.getElementById('pass').value);
var iv = CryptoJS.lib.WordArray.random(128 / 8);
window.bits = [];
window.aesEncryptor = CryptoJS.algo.AES.createEncryptor(key, {iv: iv});
// LOOP THROUGH BYTES AND PROGRESSIVELY ENCRYPT
var startByte = 0;
var endByte = 0;
while(startByte < document.querySelector('input[type=file]').files[0].size - 1){
endByte = startByte + 1000000;
readBlob(startByte, endByte);
startByte = endByte;
}
// FINALIZE ENCRYPTION AND UPLOAD
var encrypted = aesEncryptor.finalize();
encrypted = encodeURIComponent(encrypted);
var filename = document.getElementById('fileinput').value;
var file_type = document.getElementById('fileinput').files[0].type;
var url = 'data=' + encrypted + '&filename=' + filename + '&filetype=' + file_type;
$.ajax({
url: 'myphpscript.php',
type: 'POST',
data: url
}).success(function(data){
// Display encrypted data
document.getElementById('status').innerHTML = 'Upload Complete.';
});
alert(encrypted);
}
</script>
So your problem is the line var encrypted = aesEncryptor.finalize();
This is not the encrypted file, but the final 'chunk' produced by the CryptoJS.AES finalizer.
you need to append that to the end of the window.bits buffer to yield the fully encrypted file.
Also, you shouldn't be using window.bits.push, you should keep hold of a reference to each chunk like this (psuedocode):
var prog;
//then in the loop, if chunk is null assign to chunk or else concat:
loop:
if(!prog)
prog = cipher.process()
else
prog.concat(cipher.process())
//then finalize
prog.concat(cipher.finalize())
//now you're free to do whatever with the encrypted file:
var ciphertext = prog.toString()
One important thing to keep in mind is that the chunks may arrive to the encryptor out of order so you either have to keep track of the order that chunks went into aesEncryptor.process so that you can decrypt in the proper order later or queue the chunks and encrypt them in the proper order to begin with.

Alfresco web scripts: How do I stop processing or return early?

I have a web script in Alfresco that works when I pass in the correct arguments in my HTTP request. I have added validation similar to this snippet (source).
How can I tell Alfresco to stop processing the webscript if I find that my validation steps have failed? (If possible, I would like to do this without an else block.)
// extract folder listing arguments from URI
var verbose = (args.verbose == "true" ? true : false);
var folderpath = url.templateArgs.folderpath;
// search for folder within Alfresco content repository
var folder = roothome.childByNamePath(folderpath);
// validate that folder has been found
if (folder == undefined || !folder.isContainer) {
status.code = 404;
status.message = "Folder " + folderpath + " not found.";
status.redirect = true;
// ********* HOW DO I TELL ALFRESCO TO STOP PROCESSING HERE? ************
}
// perform some business logic with the parameters that passed validation......
// ********* I DO NOT WANT TO COME HERE IF VALIDATION FAILS ************
// construct model for response template to render
model.verbose = verbose;
model.folder = folder;
The trick here is to wrap your code in a function (usually called main by convention). Just call that function and return from that function if you want to stop processing. Like so:
function main() {
// extract folder listing arguments from URI
var verbose = (args.verbose == "true" ? true : false);
var folderpath = url.templateArgs.folderpath;
// search for folder within Alfresco content repository
var folder = roothome.childByNamePath(folderpath);
// validate that folder has been found
if (folder == undefined || !folder.isContainer) {
status.code = 404;
status.message = "Folder " + folderpath + " not found.";
status.redirect = true;
return;
}
// Do stuff with the folder
}
main();

Asynchronous multipart uploads to Amazon S3 with ASP.NET

I am able to initiate asynchronous uploads to S3, however they are somehow not ending up as a file inside my S3 bucket and I see an error 'WithPartETags cannot be empty'. Here is the complete code
InitiateMultipartUploadRequest initRequest =
new InitiateMultipartUploadRequest()
.WithBucketName(existingBucketName)
.WithKey(Path.Combine(S3Path + "/", finfo.Name));
InitiateMultipartUploadResponse initResponse =
s3Client.InitiateMultipartUpload(initRequest);
// 2. Upload Parts.
long contentLength = finfo.Length;
long partSize = 15728640;//52428800-50MB 104857600- 100 MB - 5242880 - 5 MB
try
{
long filePosition = 0;
for (int i = 1; filePosition < contentLength; i++)
{
// Create request to upload a part.
UploadPartRequest uploadRequest = new UploadPartRequest()
.WithBucketName(existingBucketName)
.WithKey(Path.Combine(S3Path + "/", finfo.Name))
.WithUploadId(initResponse.UploadId)
.WithPartNumber(i)
.WithPartSize(partSize)
.WithFilePosition(filePosition)
.WithFilePath(finfo.FullName);
// Upload part and add response to our list.
//uploadResponses.Add(s3Client.UploadPart(uploadRequest));
IAsyncResult ar = s3Client.BeginUploadPart(uploadRequest, null, null);
ListObj.Add(new ThreadList() { _iasyncResult = ar });
filePosition += partSize;
Console.WriteLine("Length Written - " + filePosition + " .Content Length - " + contentLength);
}
bool uploadsComplete = false;
while (!uploadsComplete)
{
bool individualuploadscomplete = true;
foreach (var obj in ListObj)
{
if (!obj._iasyncResult.IsCompleted)
{
individualuploadscomplete = false;
break;
}
}
if (individualuploadscomplete)
{
uploadsComplete = true;
}
}
foreach (var obj in ListObj)
{
s3Client.EndUploadPart(obj._iasyncResult);
}
//// Step 3: complete.
CompleteMultipartUploadRequest compRequest =
new CompleteMultipartUploadRequest()
.WithBucketName(existingBucketName)
.WithKey(Path.Combine(S3Path + "/", finfo.Name))
.WithUploadId(initResponse.UploadId);
//.WithPartETags(uploadResponses);
CompleteMultipartUploadResponse completeUploadResponse =
s3Client.CompleteMultipartUpload(compRequest);
Not sure why you have the setting of the PartETags commented out for the complete multipart upload call but you need to add that code back in. Also when you are calling the EndUploadPart method you need to capture that UploadResponse that comes back from that.
You also might want to look into the TransferUtility found in the Amazon.S3.Transfer namespace. Its upload methods are designed to handle what you are attempting to accomplish for large objects, see Using the High-Level .NET API for Multipart Upload for details and example snippets.

Umbraco v4 vs Cute AJAX Uploader Control

I have a custom user control that i use in a page in Umbraco CMS... since upgrading to version 4, it seems this user control wont work any longer.
The user control contains an ajax uploader control (support request post here: http://cutesoft.net/forums/53732/ShowThread.aspx#53732), which allows users to upload images, then displays the uploaded images to the user. The control and image displays are contained within an UpdatePanel, which is where this problem is - seems the data getting sent back to the updatePanel is not valid, so the client is spitting the dummy and throwing this error:
Sys.WebForms.PageRequestManagerParserErrorException: The message received from the server could not be parsed. Common causes for this error are when the response is modified by calls to Response.Write(), response filters, HttpModules, or server trace is enabled.
Details: Error parsing near '
<!DOCTYPE html PUBL'.
I think its somethihng to do with how Master Pages is implemented in Umbraco v4 that is causing this. Any ideas as to why this may have happened, and what i can look at to try to solve it?
FYI, here's a blog post that describes the error and its possible causes:
http://weblogs.asp.net/leftslipper/archive/2007/02/26/sys-webforms-pagerequestmanagerparsererrorexception-what-it-is-and-how-to-avoid-it.aspx
i'm doing any Response.write or Response.Redirect in the updatePanel
I'm not using any response filters
I've disabled server trace
I'm not using response.transfer
But, regardless of the above, this works fine using the same usercontrol on an Umbraco v3 site, which leads me to believe its somethign to do with v4 that's caused this.
Any suggestions greatly appreciated
I know that this whole answer is not directly a fix for your problem, but more like a workaround. this is because I am not familiar with the custom control you use.
i will however take a look tonight at your problem and see if i can find a solution for the code and plugin you use currently.
in the mean time i might give you some idea of the ajax upload i am using myself.
i know its a big chunk of code, but if you are interested you can go for it :)
my example case
I have an upload control in my own website and it works perfectly with umbraco.
the form and upload are powered with jQuery (upload is handled by jQuery.AjaxUpload plugin)
and i created a generic handler inside my umbraco folder which handles the file on the server.
creating a media item in the media library for it (and in my case beeing an avatar uploader on your profile page, it also adds the newly created mediaitem to the member's avatar property)
jQuery code: (stored in script block in the head of your page, or in a separate script)
initializeChangeAvatarForm = function() {
var button = $('#submitChangeAvatar'), interval;
new AjaxUpload(button,{
action: '/umbraco/AjaxFileUpload.ashx',
name: 'myfile',
onSubmit : function(file, ext){
// change button text to uploading + add class (with animating background loading image)
button.text('Uploading').addClass('loading');
// If you want to allow uploading only 1 file at time,
// you can disable upload button
this.disable();
},
onComplete: function(file, response){
button.text('Upload nieuw').removeClass('loading');
// Although plugins emulates hover effect automatically,
// it doens't work when button is disabled
button.removeClass('hover');
window.clearInterval(interval);
// enable upload button
this.enable();
}
});
};
$(document).ready(function(){
initializeChangeMailForm();
});
html code in your body:
<div id="container"><h2>Upload Avatar</h2><button class="button" id="submitChangeAvatar" type="button">Upload new</button></div>
jQuery ajaxupload plugin: (/scripts/jQuery.ajaxupload.js)
'since this code is too long i added a link directly to the .js file i use
'and another link to the page where i got the plugin
handler .ashx: (stored inside /umbraco/AjaxFileUpload.ashx)
using System;
using System.Collections;
using System.Data;
using System.Web;
using System.Web.SessionState;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.IO;
using System.Xml;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using umbraco.BusinessLogic;
using umbraco.cms.businesslogic.member;
namespace SH.umbServices
{
/// <summary>
/// Summary description for $codebehindclassname$
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class AjaxFileUpload : IHttpHandler, IRequiresSessionState
{
public void ProcessRequest(HttpContext context)
{
string strResponse = "error";
try
{
//string strFileName = Path.GetFileName(context.Request.Files[0].FileName);
//string strExtension = Path.GetExtension(context.Request.Files[0].FileName).ToLower();
//string strSaveLocation = context.Server.MapPath("../images/temp") + "\\" + strFileName;
//context.Request.Files[0].SaveAs(strSaveLocation);
UmbracoSave(context);
strResponse = "success";
}
catch
{
}
context.Response.ContentType = "text/plain";
context.Response.Write(strResponse);
}
public bool IsReusable
{
get
{
return false;
}
}
#region "umbMediaItem"
protected string UmbracoSave(HttpContext context)
{
string mediaPath = "";
if (context.Request.Files[0] != null)
{
if (context.Request.Files[0].FileName != "")
{
// Find filename
string _text = context.Request.Files[0].FileName;
string _ext = Path.GetExtension(context.Request.Files[0].FileName);
string filename;
string _fullFilePath;
//filename = _text.Substring(_text.LastIndexOf("\\") + 1, _text.Length - _text.LastIndexOf("\\") - 1).ToLower();
filename = Path.GetFileName(_text);
string _filenameWithoutExtention = filename.Replace(_ext, "");
int _p = 1212; // parent node.. -1 for media root)
// create the Media Node
umbraco.cms.businesslogic.media.Media m = umbraco.cms.businesslogic.media.Media.MakeNew(
_filenameWithoutExtention, umbraco.cms.businesslogic.media.MediaType.GetByAlias("image"), User.GetUser(0), _p);
// Create a new folder in the /media folder with the name /media/propertyid
System.IO.Directory.CreateDirectory(System.Web.HttpContext.Current.Server.MapPath(umbraco.GlobalSettings.Path + "/../media/" + m.Id.ToString()));
_fullFilePath = System.Web.HttpContext.Current.Server.MapPath(umbraco.GlobalSettings.Path + "/../media/" + m.Id.ToString() + "/" + filename);
context.Request.Files[0].SaveAs(_fullFilePath);
// Save extension
//string orgExt = ((string)_text.Substring(_text.LastIndexOf(".") + 1, _text.Length - _text.LastIndexOf(".") - 1));
string orgExt = Path.GetExtension(context.Request.Files[0].FileName).ToLower();
orgExt = orgExt.Trim(char.Parse("."));
try
{
m.getProperty("umbracoExtension").Value = orgExt;
}
catch { }
// Save file size
try
{
System.IO.FileInfo fi = new FileInfo(_fullFilePath);
m.getProperty("umbracoBytes").Value = fi.Length.ToString();
}
catch { }
// Check if image and then get sizes, make thumb and update database
if (",jpeg,jpg,gif,bmp,png,tiff,tif,".IndexOf("," + orgExt + ",") > 0)
{
int fileWidth;
int fileHeight;
FileStream fs = new FileStream(_fullFilePath,
FileMode.Open, FileAccess.Read, FileShare.Read);
System.Drawing.Image image = System.Drawing.Image.FromStream(fs);
fileWidth = image.Width;
fileHeight = image.Height;
fs.Close();
try
{
m.getProperty("umbracoWidth").Value = fileWidth.ToString();
m.getProperty("umbracoHeight").Value = fileHeight.ToString();
}
catch { }
// Generate thumbnails
string fileNameThumb = _fullFilePath.Replace("." + orgExt, "_thumb");
generateThumbnail(image, 100, fileWidth, fileHeight, _fullFilePath, orgExt, fileNameThumb + ".jpg");
image.Dispose();
}
mediaPath = "/media/" + m.Id.ToString() + "/" + filename;
m.getProperty("umbracoFile").Value = mediaPath;
m.XmlGenerate(new XmlDocument());
Member mbr = Member.GetCurrentMember();
umbraco.cms.businesslogic.property.Property avt = mbr.getProperty("memberAvatar");
avt.Value = m.Id;
mbr.XmlGenerate(new XmlDocument());
mbr.Save();
//string commerceFileName = mediaPath;
//CommerceSave(commerceFileName);
}
}
return mediaPath;
}
protected void generateThumbnail(System.Drawing.Image image, int maxWidthHeight, int fileWidth, int fileHeight, string fullFilePath, string ext, string thumbnailFileName)
{
// Generate thumbnail
float fx = (float)fileWidth / (float)maxWidthHeight;
float fy = (float)fileHeight / (float)maxWidthHeight;
// must fit in thumbnail size
float f = Math.Max(fx, fy); //if (f < 1) f = 1;
int widthTh = (int)Math.Round((float)fileWidth / f); int heightTh = (int)Math.Round((float)fileHeight / f);
// fixes for empty width or height
if (widthTh == 0)
widthTh = 1;
if (heightTh == 0)
heightTh = 1;
// Create new image with best quality settings
Bitmap bp = new Bitmap(widthTh, heightTh);
Graphics g = Graphics.FromImage(bp);
g.SmoothingMode = SmoothingMode.HighQuality;
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
g.PixelOffsetMode = PixelOffsetMode.HighQuality;
// Copy the old image to the new and resized
Rectangle rect = new Rectangle(0, 0, widthTh, heightTh);
g.DrawImage(image, rect, 0, 0, image.Width, image.Height, GraphicsUnit.Pixel);
// Copy metadata
ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();
ImageCodecInfo codec = null;
for (int i = 0; i < codecs.Length; i++)
{
if (codecs[i].MimeType.Equals("image/jpeg"))
codec = codecs[i];
}
// Set compresion ratio to 90%
EncoderParameters ep = new EncoderParameters();
ep.Param[0] = new EncoderParameter(Encoder.Quality, 90L);
// Save the new image
bp.Save(thumbnailFileName, codec, ep);
bp.Dispose();
g.Dispose();
}
#endregion
}
}
I hope this shed some light on what i use.
Pfew,..That's a lot of code.
I was only interessted in saving media in Umbraco but it's nice to see a jQuery upload too.
What upload jQuery lib your using? I've found serveral.
You could make the code a bit simpler by using Path.Combine, FileInfo.Extension merging if's and a few extra variables here an there. But hey I've got Resharper to make my live easier.

Resources