How do I:
- Upload a file (no problem here, I can do this)
- Rename the file
- Grab the filename after the file successfully uploads (on postback)
I need to tie this together with a database, and I'm a little confused on how to do that. I DO NOT want to store the file IN the database. I just need the filename. Aside from that, I'm golden.
Plz help quick. I have two projects where I need to do this both happening at the same time.
Cool uploader, by the way. Very easy to work with so far.
18 Answers, 1 is accepted
You are not allowed to change the file name prior uploading, however you can do that after the file is uploaded on the server and before it is saved. On postback you can do the following in order to save the files with whatever name you want:
foreach (UploadedFile file in RadUpload1.UploadedFiles)
{
string fullPath = Server.MapPath("~/Uploads");
string fileName = "name_of_your_chouce";
file.SaveAs(Path.Combine(fullPath, fileName + file.GetExtension()));
// impelement your database insert here...
}
In order to obtain the client-side name of an uploaded file you can use the GetName() method of the UploadedFile class
Kind regards,
Genady Sergeev
the Telerik team
Instantly find answers to your questions on the new Telerik Support Portal.
Check out the tips for optimizing your support resource searches.
protected void Page_Load(object sender, EventArgs e) |
{ |
if ((IsPostBack) && (RadUpload1.UploadedFiles.Count > 0)) |
{ |
HandleUpload(); |
} |
} |
protected void HandleUpload() |
{ |
foreach (UploadedFile file in RadUpload1.UploadedFiles) |
{ |
string fullPath = Server.MapPath("/uploads/EntertainmentFeatureImages/"); |
string fileName = DateTime.Now.ToBinary().ToString(); |
file.SaveAs(Path.Combine(fullPath, fileName + file.GetExtension())); |
// impelement your database insert here... |
lblResults.Text = "<p>" + fileName + file.GetExtension() + " has been added. Add another?</p>"; |
} |
} |
Sorry, I still feel a bit new to C#. This is much easier than my previous language, but there's a few things I'm definitely learning...
Please make sure that your RadUpload declaration ( in the aspx part ) does not contain property Target Folder. If you have the TargetFolder property set declaratively and in the same time save the uploaded file using the SaveAs() method this will lead to "double save". For your convenience, I have prepared sample demo project using the very code that you have provided. It shows that an uploaded file is saved only once.
Regards,
Genady Sergeev
the Telerik team
Instantly find answers to your questions on the new Telerik Support Portal.
Check out the tips for optimizing your support resource searches.
So where is the file being saved if I don't specify a location first declaratively? In temp? I know in PHP (my previous language of choice) you specify the location after the file has gone through filtering and been uploaded. I guess it's the same here and I had just gotton confused.
Thanks. I appreciate the help. This is really going to help get two projects off the ground quickly. It's rough learning a new language, but I love the Aha! moments. Thanks again.
All uploaded files larger than 256kb are buffered to the disk rather than saved to the server memory. Once the upload finishes, the uploaded files should be saved with the SaveAs() method ( and this is exactly what the TargetFolder property does internally ). If the SaveAs method is not invoked, the related file is disposed and is not saved to the disk.
Regards,
Genady Sergeev
the Telerik team
Instantly find answers to your questions on the new Telerik Support Portal.
Check out the tips for optimizing your support resource searches.
I'm trying to rename my files after they have been uploaded. Please help me in 2 areas:
1. I have the RadUpload embedded in a column in a RadGrid. The problem is that the RadUpload1 control is not recognized in the code-behind.
<telerik:GridTemplateColumn UniqueName="Upload" ShowFilterIcon="False" AllowFiltering="False"
ShowSortIcon="False" HeaderText="Funding Document(s)">
<ItemTemplate>
...
</ItemTemplate>
<EditItemTemplate>
<telerik:RadUpload ID="RadUpload1" runat="server" OverwriteExistingFiles="false"
Skin="WebBlue" />
</EditItemTemplate>
</telerik:GridTemplateColumn>
2. I would like to change the name of each file uploaded. How can I use the data in a column of the record as the file name?
Example: I would like to change the file name to "JohnSmith1" for his record. There may be multiple files uploaded for each record.
Name City State Upload File
JohnSmith Springdale VA (RadUpload)
Thanks,
Patrick
protected void RadGrid1_InsertCommand(object source, Telerik.Web.UI.GridCommandEventArgs e) |
{ |
RadUpload upload = e.Item.FindControl("RadUpload1") as RadUpload; |
} |
Genady Sergeev
the Telerik team
Instantly find answers to your questions on the newTelerik Support Portal.
Check out the tipsfor optimizing your support resource searches.
Thanks for the quick reply and for your help.
It's not working as expected. It doesn't even upload the file now. I put a breakpoint in the code-behind at the
Protected
Sub RadGrid1_InsertCommand
and it doesn't stop the process after I update the RadGrid. Should I be using an RadGrid1_UpdateCommand?
Also, how could parameterize the data in the GridBoundColumn "Proposal Number", as you did with the TextBox.Text in the example?
function checkExtension(radUpload, eventArgs) | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
{ | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
var input = eventArgs.get_fileInputField(); | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
if (!radUpload.isExtensionValid(input.value)) | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
{ | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
var inputs = radUpload.getFileInputs(); | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
for (i = 0; i < inputs.length; i++) | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
{ | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
if (inputs[i] == input) | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
{ | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
alert(input.value + " does not have a valid extension."); | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
radUpload.clearFileInputAt(i); | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
break; | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
} | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
} | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
} | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
}
|
Thanks for any help you can give me!!
Patrick
As it is, your Grid will never execute an Insert command. This column:
<telerik:GridEditCommandColumn EditText="Upload" HeaderText="Upload Document(s)" |
UniqueName="UploadDocuments" UpdateText="Upload" /> |
will trigger an update command. So, the insert event not firing is correct and expected behavior. I suggest you to modify the MasterTable declaration the following way:
<MasterTableView AutoGenerateColumns="False".... |
CommandItemDisplay="Top" > |
<Columns> |
CommandItemDisplay will put an insert button on the top of the grid. This will cause the insert event to fire and the uploaded file to be saved. I am attaching my modified example for reference ( Default2.aspx )
Kind regards,
Genady Sergeev
the Telerik team
Instantly find answers to your questions on the new Telerik Support Portal.
Check out the tips for optimizing your support resource searches.
Thanks for the reply.
I may be a little confused. Correct me if I'm wrong about this, but doesn't the Insert command imply that the user will insert a new record into the DB? I want to update the record by adding a file to a folder and set the file name equal to the Text or String property of the data in the Proposal Number column for that record. Then I want to display the file name as a link in a details view of that record.
I changed the RadGrid1_InsertCommand to RadGrid1_UpdateCommand. That fired when I clicked the Update button after selecting the file to upload for that record. However, the While loop in the SaveFiles Sub is an infinite loop. I looked at the Locals windows while debugging and the integer i just kept incrementing by 1 each time. It never saved the file to the folder.
Also, how could parameterize the data in the GridBoundColumn "Proposal Number", as you did with the TextBox.Text in the example?
Again, thanks for your help,
Patrick
<telerik:RadGrid ID="RadGrid1" runat="server" ShowStatusBar="True" Skin="WebBlue" |
DataSourceID="SqlFundingPackageListing" GridLines="None" AllowFilteringByColumn="True" |
AllowPaging="True" AllowSorting="True" PageSize="15" OnUpdateCommand="RadGrid1_UpdateCommand"> |
Protected Sub RadGrid1_UpdateCommand(ByVal source As Object, ByVal e As Telerik.Web.UI.GridCommandEventArgs) |
Dim upload As RadUpload = TryCast(e.Item.FindControl("RadUpload1"), RadUpload) |
Dim fileName As String = "File" |
SaveFiles(upload, fileName) |
End Sub |
Private Sub SaveFiles(ByVal upload As RadUpload, ByVal fileName As String) |
Dim i As Integer = 1 |
For Each file As UploadedFile In upload.UploadedFiles |
Dim path As String = Server.MapPath("~/Uploads") |
If Not System.IO.File.Exists(System.IO.Path.Combine(path, fileName + file.GetExtension())) Then |
file.SaveAs(System.IO.Path.Combine(path, fileName + file.GetExtension())) |
Else |
Dim fullName As String = System.IO.Path.Combine(path, String.Concat(fileName, i.ToString(), file.GetExtension())) |
While System.IO.File.Exists(fullName) |
fullName = System.IO.Path.Combine(path, String.Concat(fileName, i.ToString(), file.GetExtension())) |
i += 1 |
End While |
file.SaveAs(fullName) |
End If |
Next |
End Sub |
Now I need to fingure out how to name the file the Text or String property of the data in the Proposal Number column for that record.
Also, how would I save the file to a folder on the server, such as "H:\UploadFiles"? I tried to put that in instead of "~/Uploads" but it gave me an error stating that 'H:\UploadFiles' is not a valid virtual path.
Thanks!
Patrick
You can convert the Proposal bound column to a template one. Thus you will be able to use the FindControl method in order to find the TextBox that holds the column's value. Example:
<telerik:GridTemplateColumn DataField="ProposalNumber" HeaderText="Proposal Number" |
SortExpression="Proposal Number" UniqueName="Proposal Number"> |
<ItemTemplate> |
<asp:Label runat="server" ID="LblProposal" Text='<%# Eval("ProposalNumber") %>'></asp:Label> |
</ItemTemplate> |
<EditItemTemplate> |
<asp:TextBox runat="server" ID="TxtProposal" Text='<%# Bind("ProposalNumber") %>'></asp:TextBox> |
</EditItemTemplate> |
</telerik:GridTemplateColumn> |
and then get the text like this:
Protected Sub RadGrid1_UpdateCommand(ByVal source As Object, ByVal e As Telerik.Web.UI.GridCommandEventArgs) |
Dim upload As RadUpload = TryCast(e.Item.FindControl("RadUpload1"), RadUpload) |
Dim proposalNumber As String = TryCast(e.Item.FindControl("TxtProposal"), TextBox).Text |
Dim fileName As String = "File" |
SaveFiles(upload, fileName) |
End Sub |
As for the Save issue, there should be no problem to save a file like this:
Dim path As String = "C:\Work" |
If Not System.IO.File.Exists(System.IO.Path.Combine(path, fileName + file.GetExtension())) Then |
file.SaveAs(System.IO.Path.Combine(path, fileName + file.GetExtension())) |
Kind regards,
Genady Sergeev
the Telerik team
Instantly find answers to your questions on the new Telerik Support Portal.
Check out the tips for optimizing your support resource searches.
Works like a charm :-)
Now for the next part...
I am storing the uploaded files on a local drive. The end users need to access the uploaded files. So, I think the best way to handle this would be to have a details view for each record. Then, I could place a link to that record's related uploaded file(s) in the details view.
How should I establish the data source for this? Should I attempt to call the files from a stored procedure and then call the stored procedure in the data source?
Thoughts? Suggestions?
Thanks for all your help!!
Patrick
<
MasterTableView
AutoGenerateColumns
=
"False"
DataSourceID
=
"SqlDataSource1"
DataKeyNames
=
"ImageID"
CommandItemDisplay
=
"Top"
>
<
Columns
>
<
telerik:GridBoundColumn
DataField
=
"ImageName"
HeaderText
=
"Proposal Number"
SortExpression
=
"Proposal Number"
UniqueName
=
"ProposalNumber"
>
</
telerik:GridBoundColumn
>
<
telerik:GridTemplateColumn
UniqueName
=
"Upload"
ShowFilterIcon
=
"False"
AllowFiltering
=
"False"
ShowSortIcon
=
"False"
HeaderText
=
"Funding Document(s)"
>
<
ItemTemplate
>
...</
ItemTemplate
>
<
EditItemTemplate
>
<
telerik:RadUpload
ID
=
"RadUpload1"
runat
=
"server"
OverwriteExistingFiles
=
"false"
Skin
=
"WebBlue"
MaxFileInputsCount
=
"5"
AllowedFileExtensions
=
".pdf,.docx,.doc"
OnClientFileSelected
=
"checkExtension"
/>
</
EditItemTemplate
>
</
telerik:GridTemplateColumn
>
<
telerik:GridButtonColumn
HeaderText
=
"Upload Document(s)"
UniqueName
=
"UploadDocuments"
CommandName
=
"Insert"
>
</
telerik:GridButtonColumn
>
</
Columns
>
<
EditFormSettings
>
<
EditColumn
UniqueName
=
"EditCommandColumn1"
/>
</
EditFormSettings
>
</
MasterTableView
>
You will need to use template column and manually add a text box as an edit template. Then from the OnClientFileSelected event of RadUpload you can grab reference to the ImageName text box and set its value to be equal to the one of the the file input. Here is some sample code:
<
script
type
=
"text/javascript"
>
function checkExtension(radUpload, eventArgs)
{
var input = eventArgs.get_fileInputField();
var $ = $telerik.$;
$(".ImageName:visible").val(input.value);
}
</
script
>
<
div
>
<
telerik:RadGrid
ID
=
"RadGrid1"
runat
=
"server"
AutoGenerateDeleteColumn
=
"True"
AutoGenerateEditColumn
=
"True"
AllowAutomaticInserts
=
"True"
GridLines
=
"None"
AllowAutomaticDeletes
=
"True"
DataSourceID
=
"SqlDataSource1"
oninsertcommand
=
"RadGrid1_InsertCommand"
>
<
HeaderContextMenu
>
<
CollapseAnimation
Type
=
"OutQuint"
Duration
=
"200"
></
CollapseAnimation
>
</
HeaderContextMenu
>
<
PagerStyle
Mode
=
"NextPrevAndNumeric"
/>
<
MasterTableView
AutoGenerateColumns
=
"False"
DataSourceID
=
"SqlDataSource1"
DataKeyNames
=
"ImageID"
CommandItemDisplay
=
"Top"
>
<
Columns
>
<
telerik:GridTemplateColumn
UniqueName
=
"ImageName"
>
<
ItemTemplate
>
...</
ItemTemplate
>
<
EditItemTemplate
>
<
asp:TextBox
runat
=
"server"
ID
=
"TextBox1"
CssClass
=
"ImageName"
></
asp:TextBox
>
</
EditItemTemplate
>
</
telerik:GridTemplateColumn
>
<
telerik:GridTemplateColumn
UniqueName
=
"Upload"
ShowFilterIcon
=
"False"
AllowFiltering
=
"False"
ShowSortIcon
=
"False"
HeaderText
=
"Funding Document(s)"
>
<
ItemTemplate
>
...</
ItemTemplate
>
<
EditItemTemplate
>
<
telerik:RadUpload
ID
=
"RadUpload1"
runat
=
"server"
OverwriteExistingFiles
=
"false"
Skin
=
"WebBlue"
MaxFileInputsCount
=
"5"
AllowedFileExtensions
=
".pdf,.docx,.doc"
OnClientFileSelected
=
"checkExtension"
/>
</
EditItemTemplate
>
</
telerik:GridTemplateColumn
>
<
telerik:GridButtonColumn
HeaderText
=
"Upload Document(s)"
UniqueName
=
"UploadDocuments"
CommandName
=
"Insert"
>
</
telerik:GridButtonColumn
>
</
Columns
>
<
EditFormSettings
>
<
EditColumn
UniqueName
=
"EditCommandColumn1"
/>
</
EditFormSettings
>
</
MasterTableView
>
<
FilterMenu
>
<
CollapseAnimation
Type
=
"OutQuint"
Duration
=
"200"
></
CollapseAnimation
>
</
FilterMenu
>
</
telerik:RadGrid
>
Kind regards,
Genady Sergeev
the Telerik team
Some body please hepl me.
<%
@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="uploadinggrid1.Default" %>
<%
@ Register Assembly="Telerik.Web.UI" Namespace="Telerik.Web.UI" TagPrefix="telerik" %>
<!
DOCTYPE html>
<
html xmlns="http://www.w3.org/1999/xhtml">
<
head runat="server">
<title></title>
<telerik:RadScriptBlock ID="RadScriptBlock1" runat="server">
<script type="text/javascript">
 
function conditionalPostback(e, sender) {
var theRegexp = new RegExp("\.UpdateButton$|\.PerformInsertButton$", "ig");
if (sender.get_eventTarget().match(theRegexp)) {
var upload = $find(window['UploadId']);
//AJAX is disabled only if file is selected for upload
if (upload.getFileInputs()[0].value != "") {
sender.set_enableAjax(
false);
}
}
}
function validateRadUpload(source, e) {
alert(
"true");
e.IsValid =
false;
var upload = $find(source.parentNode.getElementsByTagName('div')[0].id);
var inputs = upload.getFileInputs();
for (var i = 0; i < inputs.length; i++) {
//check for empty string or invalid extension
if (inputs[i].value != "" && upload.isExtensionValid(inputs[i].value)) {
e.IsValid =
true;
break;
}
}
}
 
 
</script>
</telerik:RadScriptBlock>
</
head>
<
body>
<form id="form1" runat="server">
<div>
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<telerik:RadAjaxPanel ID="RadAjaxPanel1" runat="server" Height="200px" Width="300px">
<telerik:RadGrid runat="server" ID="MyRadGrid" AutoGenerateColumns="false" OnItemDataBound="MyRadGrid_ItemDataBound" OnNeedDataSource="MyRadGrid_NeedDataSource" OnItemCreated="MyRadGrid_ItemCreated" OnInsertCommand="MyRadGrid_InsertCommand" >
<MasterTableView CommandItemDisplay="Top" CommandItemSettings-AddNewRecordText="Add New File">
<Columns>
<telerik:GridEditCommandColumn></telerik:GridEditCommandColumn>
<telerik:GridTemplateColumn HeaderText="Upload" UniqueName="Upload">
<ItemTemplate>
<%
#Eval("Col1")%>
</ItemTemplate>
<EditItemTemplate>
<telerik:RadUpload runat="server" ID="RadUpload" ControlObjectsVisibility="None" />
</EditItemTemplate>
</telerik:GridTemplateColumn>
</Columns>
</MasterTableView>
</telerik:RadGrid>
</telerik:RadAjaxPanel>
</div>
</form>
</
body>
</
html>
Cs code is :
using
System;
using
System.Collections.Generic;
using
Microsoft.VisualBasic;
using
System.Linq;
using
System.Web;
using
System.Web.UI;
using
System.Web.UI.WebControls;
using
System.Diagnostics;
using
System.Data;
using
Telerik.Web.UI;
namespace
uploadinggrid1
{
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void MyRadGrid_NeedDataSource(object sender, Telerik.Web.UI.GridNeedDataSourceEventArgs e)
{
MyRadGrid.DataSource = GridDataSource();
}
private DataTable GridDataSource()
{
DataTable dt = new DataTable();
dt.Columns.Add(
"Col1");
DataRow dr = dt.NewRow();
dt.Rows.Add(dr);
return dt;
}
protected void MyRadGrid_ItemDataBound(object sender, GridItemEventArgs e)
{
if ((e.Item) is GridEditableItem && e.Item.IsInEditMode)
{
RadUpload upload = e.Item.FindControl("RadUpload") as RadUpload;
RadAjaxPanel1.ResponseScripts.Add(
string.Format("window['UploadId'] = '{0}';", upload.ClientID));
}
}
protected void MyRadGrid_ItemCreated(object sender, GridItemEventArgs e)
{
if (e.Item is GridEditableItem && e.Item.IsInEditMode)
{
RadUpload upload = e.Item.FindControl("RadUpload") as RadUpload;
CustomValidator validator = new CustomValidator();
validator.ErrorMessage =
"Please select file to upload";
validator.ClientValidationFunction =
"validateRadUpload";
validator.Display =
ValidatorDisplay.Dynamic;
((
TableCell)upload.Parent).Controls.Add(validator);
}
}
protected void MyRadGrid_InsertCommand(object sender, GridCommandEventArgs e)
{
//GridEditFormInsertItem item = (GridEditFormInsertItem)e.Item;
//RadUpload upload = e.Item.FindControl("RadUpload") as RadUpload;
//string name = upload.UploadedFiles[0].FileName;
}
 
}
}