I'm performing upload of files into DB with Telerik's ASP.NET RadAsyncpload, which is very similar to the normal fileUpload.
My problem is that, when using the variable to store the Data, it saves as "null". in alternative i tried to use Server.MapPath, which is for is turn saving the folder localtion instead of the File.
What am i doing wrong?
//partial class declarations
(...)
string Ficheiro = string.Empty;
string FileTipo = string.Empty;
byte[] fileBytes = null;
//Save method, triggered by save button after upload
public void SaveFile(object sender, EventArgs e)
{
ListagemTimesheet model = new ListagemTimesheet();
model.IDRecursoHumano = Convert.ToInt32(rdpInvestigadorE.Text);
model.IDEstadoTimesheet = Convert.ToInt32(rcbEstado.SelectedValue);
model.Observações = Obervaçoestxt.Text;
model.AssinaturaTimesheet = txtAssinaturaTimesheet.Text;
model.DataEnvio = DataEnvio.SelectedDate.Value;
if (Objecto.ID > 0)
{
model.ID = Convert.ToInt32(FileID.Text);
if (!string.IsNullOrEmpty(Ficheiro) && FileTipo != null)
{
model.FileName = Path.GetFileNameWithoutExtension(Ficheiro); //FileName
model.FileTipo = Path.GetExtension(FileTipo); //FileExtension
model.FileContent = fileBytes; //Content null
model.FileContent = Encoding.ASCII.GetBytes(HttpContext.Current.Server.MapPath("~/TargetFiles/ + model.FileName")); //Content saved is location of the folder
//Upload method
public void RadAsyncUpload1_FileUploaded(object sender, FileUploadedEventArgs e)
{
RadAsyncUpload1.Visible = false;
Stream fileStream = e.File.InputStream;
Ficheiro = e.File.FileName; // sintaxe metodo
FileTipo = e.File.ContentType;
e.IsValid = true;
byte[] fileBytes = new byte[fileStream.Length - 1 + 1];
fileStream.Read(dados, 0, System.Convert.ToInt32(fileStream.Length));
fileStream.Close();
}
You appear to be reading your file data into a local variable called dados, but is never assigned to the global variable.
Your file data should most likely go into the fileBytes variable, to enable your SaveFile function to read the value.
So you should read the fileStream directly into your fileBytes variable.
...
byte[] fileBytes = new byte[fileStream.Length - 1 + 1];
...
Full code
//Save method, triggered by save button after upload
public void SaveFile(object sender, EventArgs e)
{
ListagemTimesheet model = new ListagemTimesheet();
model.IDRecursoHumano = Convert.ToInt32(rdpInvestigadorE.Text);
model.IDEstadoTimesheet = Convert.ToInt32(rcbEstado.SelectedValue);
model.Observações = Obervaçoestxt.Text;
model.AssinaturaTimesheet = txtAssinaturaTimesheet.Text;
model.DataEnvio = DataEnvio.SelectedDate.Value;
if (Objecto.ID > 0)
{
model.ID = Convert.ToInt32(FileID.Text);
if (!string.IsNullOrEmpty(Ficheiro) && FileTipo != null)
{
model.FileName = Path.GetFileNameWithoutExtension(Ficheiro); //FileName
model.FileTipo = Path.GetExtension(FileTipo); //FileExtension
model.FileContent = fileBytes; // This will now be the data loaded from the filestream in your RadAsyncUpload1_FileUploaded function
// This returns the path in the content because Encoding.ASCII.GetBytes simply changes the string path to a byte array
//model.FileContent = Encoding.ASCII.GetBytes(HttpContext.Current.Server.MapPath("~/TargetFiles/ + model.FileName")); //Content saved is location of the folder
//Upload method
public void RadAsyncUpload1_FileUploaded(object sender, FileUploadedEventArgs e)
{
RadAsyncUpload1.Visible = false;
Stream fileStream = e.File.InputStream;
Ficheiro = e.File.FileName; // sintaxe metodo
FileTipo = e.File.ContentType;
e.IsValid = true;
// Read the file stream into your fileBytes variable
byte[] fileBytes = new byte[fileStream.Length - 1 + 1];
fileStream.Read(fileBytes, 0, System.Convert.ToInt32(fileStream.Length));
fileStream.Close();
}
RESOLVED!
I was missing copy the stream to the variable fileBytes.
public void RadAsyncUpload1_FileUploaded(object sender, FileUploadedEventArgs e)
{
RadAsyncUpload1.Visible = false; //false
var liItem = new HtmlGenericControl("li");
Ficheiro = e.File.FileName; // sintaxe metodo
FileTipo = e.File.ContentType;
e.IsValid = true;
e.File.InputStream.Position = 0;
fileBytes = new byte[e.File.InputStream.Length];
for (int totalBytesCopied = 0; totalBytesCopied < e.File.InputStream.Length; )
totalBytesCopied += e.File.InputStream.Read(fileBytes, totalBytesCopied, Convert.ToInt32(e.File.InputStream.Length) - totalBytesCopied); //conversao para bytes
e.File.InputStream.Close();
if (File.Exists("~/App_Data/RadUploadTemp"))
{
e.IsValid = false;
e.File.SaveAs(Server.MapPath(
Path.Combine(RadAsyncUpload1.TargetFolder, e.File.GetNameWithoutExtension() + "1" + e.File.GetExtension())));
}
}
Related
When I am saving an image, it is getting saved by the Barcode name.
But If I modify the barcode name, then the image is gone, not saving.
I have noticed while debugging that the if(System.IO.File.Exists(imageFilePath)) is not executing when I am updating the barcode. But at the time of saving a new one, its executing.
How to correct this?
Updating code
public object Update(ItemEntity item)
{
var val = _itemRepository.Save(item);
if (item.ImageFileName != string.Empty || item.ImageOriginalFileName != string.Empty)
{
string result = JsonConvert.SerializeObject(val);
var definition = new { Success = false, EntryMode = string.Empty, BarCode = string.Empty, ItemCode = string.Empty };
var info = JsonConvert.DeserializeAnonymousType(result, definition);
if (info.Success)
{
if (!string.IsNullOrEmpty(item.ImageOriginalFileName))
this.SaveImage(item.ImageFileName, (item.ImageOriginalFileName == "BARCODE" ? info.ItemCode : item.ImageOriginalFileName == "BARCODEYes" ? item.Barcode : item.ImageOriginalFileName));
}
}
if (item.DeleteImageFileName != string.Empty && item.ImageFileName == string.Empty) // Image file removed but no new image file is uploaded[Bug Id :34754 -No image is uploaded, when a user re-uploads an image after deleting a previous one.]
{
this.DeleteImage(item.DeleteImageFileName);
}
return val;
}
Saving Code
public void SaveImage(string fileName, string originalFileName)
{
string tempFileName = fileName;
if (!string.IsNullOrEmpty(tempFileName))
{
// move file from temp location to actual loation
var webAppPath = System.Web.Hosting.HostingEnvironment.MapPath("~");
var splitPath = webAppPath.Split("\\".ToCharArray()).ToList();
var upLevel = splitPath.Count - 1; // one level up
splitPath = splitPath.Take(upLevel).ToList();
var UIFolder = "WebUI";
splitPath.AddRange(new string[] { UIFolder, "Temp", "ImageUpload", CurrentSession.UserId.Value.ToString(), "ItemImage" });
var webUIPath = splitPath.Aggregate((i, j) => i + "\\" + j);
var imageFilePath = Path.Combine(webUIPath.EnsureEndsWith('\\'), tempFileName);
if (System.IO.File.Exists(imageFilePath))
{
splitPath = webAppPath.Split("\\".ToCharArray()).ToList();
upLevel = splitPath.Count - 1; // one level up
splitPath = splitPath.Take(upLevel).ToList();
splitPath.AddRange(new string[] { "Shared", "ItemImage" });
webUIPath = splitPath.Aggregate((i, j) => i + "\\" + j);
// Check existence of folder, create if not found and Delete-Create if found
if (!Directory.Exists(webUIPath))
{
Logger.Debug("Create directory :" + webUIPath);
Directory.CreateDirectory(webUIPath);
}
originalFileName = originalFileName + ".jpg";
var imagDestPath = Path.Combine(webUIPath.EnsureEndsWith('\\'), originalFileName);
if (File.Exists(imagDestPath))
{
GC.Collect();
GC.WaitForPendingFinalizers();
Logger.Debug("Delete File :" + imagDestPath);
File.Delete(imagDestPath);
}
byte[] bytes = System.IO.File.ReadAllBytes(imageFilePath);
FileStream fs = new FileStream(imagDestPath, FileMode.Create, FileAccess.Write);
BinaryWriter bw = new BinaryWriter(fs);
bw.Write(bytes);
bw.Close();
}
}
}
I am trying to Copy a TXT File in Assets over to the SD Card / Internal Storage.
All examples are in Java, is there anyway this can be done in C#?
Java Code:
final static String TARGET_BASE_PATH = "/sdcard/appname/voices/";
private void copyFilesToSdCard() {
copyFileOrDir(""); // copy all files in assets folder in my project
}
private void copyFileOrDir(String path) {
AssetManager assetManager = this.getAssets();
String assets[] = null;
try {
Log.i("tag", "copyFileOrDir() "+path);
assets = assetManager.list(path);
if (assets.length == 0) {
copyFile(path);
} else {
String fullPath = TARGET_BASE_PATH + path;
Log.i("tag", "path="+fullPath);
File dir = new File(fullPath);
if (!dir.exists() && !path.startsWith("images") && !path.startsWith("sounds") && !path.startsWith("webkit"))
if (!dir.mkdirs())
Log.i("tag", "could not create dir "+fullPath);
for (int i = 0; i < assets.length; ++i) {
String p;
if (path.equals(""))
p = "";
else
p = path + "/";
if (!path.startsWith("images") && !path.startsWith("sounds") && !path.startsWith("webkit"))
copyFileOrDir( p + assets[i]);
}
}
} catch (IOException ex) {
Log.e("tag", "I/O Exception", ex);
}
}
private void copyFile(String filename) {
AssetManager assetManager = this.getAssets();
InputStream in = null;
OutputStream out = null;
String newFileName = null;
try {
Log.i("tag", "copyFile() "+filename);
in = assetManager.open(filename);
if (filename.endsWith(".jpg")) // extension was added to avoid compression on APK file
newFileName = TARGET_BASE_PATH + filename.substring(0, filename.length()-4);
else
newFileName = TARGET_BASE_PATH + filename;
out = new FileOutputStream(newFileName);
byte[] buffer = new byte[1024];
int read;
while ((read = in.read(buffer)) != -1) {
out.write(buffer, 0, read);
}
in.close();
in = null;
out.flush();
out.close();
out = null;
} catch (Exception e) {
Log.e("tag", "Exception in copyFile() of "+newFileName);
Log.e("tag", "Exception in copyFile() "+e.toString());
}
}
How would the above code be done in C#?
Thanks.
A possible solution could look like my method to copy a database from the Assets folder to the device:
public static async Task CopyDatabaseAsync(Activity activity)
{
var dbPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), "YOUR_DATABASENAME");
if (!File.Exists(dbPath))
{
try
{
using (var dbAssetStream = activity.Assets.Open("YOUR_DATABASENAME"))
using (var dbFileStream = new FileStream(dbPath, FileMode.OpenOrCreate))
{
var buffer = new byte[1024];
int b = buffer.Length;
int length;
while ((length = await dbAssetStream.ReadAsync(buffer, 0, b)) > 0)
{
await dbFileStream.WriteAsync(buffer, 0, length);
}
dbFileStream.Flush();
dbFileStream.Close();
dbAssetStream.Close();
}
}
catch (Exception ex)
{
//Handle exceptions
}
}
}
You can call it in OnCreate with ContinueWith
CopyDatabaseAsync().ContinueWith(t =>
{
if (t.Status != TaskStatus.RanToCompletion)
return;
//your code here
});
I don't understand why I get this error... Can anyone help me?
private void button1_Click(object sender, EventArgs e, string filePath)
{
OpenFileDialog of = new OpenFileDialog();
of.ShowDialog();
Filenametext.Text = of.FileName;
//Create an instance for the openbox dialog
//And opens the explorer to select the wanted file.
{
DataRow row;
DataService m_WsData = new DataService();
string XMLFileName = ConfigurationSettings.AppSettings["XMLPath"].ToString() + DateTime.Now.Ticks.ToString() + ".xml";
FileStream fs = new FileStream(filePath, FileMode.Open);
StreamReader sr = new StreamReader(fs, System.Text.Encoding.GetEncoding("ISO-8859-1"));
{
DataSet ds = m_WsData.GEDS();
string line = "";
int lineNo = 0;
string lineStart = "";
string lineEnd = "";
string[] fileRow;
{
line = sr.ReadLine();
if (line != null)
{
fileRow = line.Split(new Char[] { ';' });
if (lineNo == 0)
{
lineStart = fileRow[0];
}
if (fileRow[0] != "00" && fileRow[0] != "99")
{
row = ds.Tables["FuelFileData"].NewRow();
row["TransNo"] = fileRow[0];
row["CustomerNo"] = fileRow[1];
row["TruckNo"] = fileRow[2];
row["FuelDate"] = fileRow[3];
row["FuelTime"] = fileRow[4];
row["Place"] = fileRow[5];
row["FuelTypeNo"] = fileRow[6];
row["FuelDescription"] = fileRow[7];
row["DriverNo"] = fileRow[8];
row["Blank"] = fileRow[9];
row["TransType"] = fileRow[10];
row["Fuel"] = fileRow[11];
row["FuelCost"] = fileRow[12];
row["MileageFile"] = fileRow[13];
row["DrivenKm"] = fileRow[14];
row["AverageConsFile"] = fileRow[15];
//row["ImportedGuid"]=fileRow[16];
}
lineEnd = fileRow[0];
lineNo++;
}
} while (line != null);
lineStart = lineStart.Trim() + lineEnd.Trim();
fs.Close();
if (lineStart == "0099")
{
ds.WriteXml(XMLFileName);
System.IO.File.Delete(XMLFileName);
}
}
}
}
Cause
You cannot add parameters on event handler methods.
The Click event is defined as
public event RoutedEventHandler Click;
which means that the handler must match the delegate RoutedEventHandler which is
public delegate void RoutedEventHandler(Object sender, RoutedEventArgs e);
Solution
Remove the string filePath parameter and pass the path via a public property.
I'm using radAsyncFileUpload to upload a file. I want to save the file contents in a database as bytes. Here's my code so far:
protected void DetailsView1_ItemInserting(object sender, DetailsViewInsertEventArgs e)
{
if (DetailsView1.CurrentMode == DetailsViewMode.Insert)
{
if (Session["ProjectId"] != null)
{
int Projectid = Convert.ToInt32(Session["ProjectId"]);
string Description = (DetailsView1.FindControl("RadEditor1") as RadEditor).Content;
RadAsyncUpload radAsyncUpload = DetailsView1.FindControl("RadAsyncUpload1") as RadAsyncUpload;
UploadedFile file = radAsyncUpload.UploadedFiles[0];
string s = file.FileName;
string path = System.IO.Path.GetFileName(s);
radAsyncUpload.UploadedFiles[0].SaveAs(Server.MapPath("Uploads/") + path);
string Contenttype = radAsyncUpload.UploadedFiles[0].ContentType;
int fileSize = radAsyncUpload.UploadedFiles[0].ContentLength;
float length = float.Parse(fileSize.ToString());
byte[] fileData = new byte[file.InputStream.Length];
file.InputStream.Read(fileData, 0, (int)file.InputStream.Length);
ProTrakEntities objEntity = new ProTrakEntities();
ProjectFile objFile = new ProjectFile();
objFile.ProjectId = Projectid;
objFile.FileName = s;
objFile.FileType = Contenttype;
objFile.FileSize = length;
objFile.CreatedBy = "admin";
objFile.CreatedDate = DateTime.Now;
objFile.Description = Description;
objFile.FileData = fileData;
objEntity.AddToProjectFiles(objFile);
objEntity.SaveChanges();
}
DetailsView1.ChangeMode(DetailsViewMode.ReadOnly);
ClientScript.RegisterStartupScript(Page.GetType(), "mykey", "CloseAndRebind('navigateToInserted');", true);
}
}
I'm getting an error while uploading at the line file.InputStream.Read(fileData, 0, (int)file.InputStream.Length);:
Could not find file 'D:\Tiru\Projects\ProTrak\App_Data\RadUploadTemp\0ngsv0wx.fxs'.
What does this error mean, and how can I get rid of it?
As em not having the edit right..
em posting ur code with little modification see if it works..
my code
protected void DetailsView1_ItemInserting(object sender, DetailsViewInsertEventArgs e)
{
if (DetailsView1.CurrentMode == DetailsViewMode.Insert)
{
if (Session["ProjectId"] != null)
{
int Projectid = Convert.ToInt32(Session["ProjectId"]);
string Description = (DetailsView1.FindControl("RadEditor1") as RadEditor).Content;
RadAsyncUpload radAsyncUpload = DetailsView1.FindControl("RadAsyncUpload1") as RadAsyncUpload;
UploadedFile file = radAsyncUpload.UploadedFiles[0];
string s = file.FileName;
string path = System.IO.Path.GetFileName(s);
string Contenttype = radAsyncUpload.UploadedFiles[0].ContentType;
int fileSize = radAsyncUpload.UploadedFiles[0].ContentLength;
float length = float.Parse(fileSize.ToString());
byte[] fileData = new byte[file.InputStream.Length];
file.InputStream.Read(fileData, 0, (int)file.InputStream.Length);
ProTrakEntities objEntity = new ProTrakEntities();
ProjectFile objFile = new ProjectFile();
objFile.ProjectId = Projectid;
objFile.FileName = s;
objFile.FileType = Contenttype;
objFile.FileSize = length;
objFile.CreatedBy = "admin";
objFile.CreatedDate = DateTime.Now;
objFile.Description = Description;
objFile.FileData = fileData;
objEntity.AddToProjectFiles(objFile);
objEntity.SaveChanges();
}
DetailsView1.ChangeMode(DetailsViewMode.ReadOnly);
ClientScript.RegisterStartupScript(Page.GetType(), "mykey", "CloseAndRebind('navigateToInserted');", true);
radAsyncUpload.UploadedFiles[0].SaveAs(Server.MapPath("Uploads/") + path);
}
}
use like this..
RadAsyncUpload radAsyncUpload = InsertItem.FindControl("AsyncUpload1") as RadAsyncUpload;
UploadedFile file = radAsyncUpload.UploadedFiles[0];
byte[] fileData = new byte[file.InputStream.Length];
file.InputStream.Read(fileData, 0, (int)file.InputStream.Length);
i can upload images to the database using linq and the listview control when referancing the e.Values method for the ListViewInsertEventArgs, but there is no such method in the ListViewEditEventArgs, so what can i use to achieve the same results?
here is my inserting code:
protected void ProjectPhotosList_ItemInserting(object sender, ListViewInsertEventArgs e)
{
FileUpload uplImage = (FileUpload)ProjectPhotosList.InsertItem.FindControl("uplImage");
Label fileuploadlbl = (Label)ProjectPhotosList.InsertItem.FindControl("fileuploadlbl");
byte[] img = null;
if (uplImage.HasFile || !uplImage.FileName.ToLower().EndsWith(".jpg"))
{
try
{
img = new byte[uplImage.PostedFile.ContentLength];
uplImage.PostedFile.InputStream.Read(img, 0, img.Length);
}
catch
{
fileuploadlbl.Text = "unable to upload " + uplImage.FileName.ToString();
}
}
if (img == null)
{
e.Cancel = true;
fileuploadlbl.Text = "Please choose a file to upload";
}
try
{
e.Values.Add("ProjectPhoto", new System.Data.Linq.Binary(img));
fileuploadlbl.Text = "File Upload Successful";
}
catch
{
fileuploadlbl.Text = "File Upload Failed, please try again";
}
}
ok so i have solved the issue! I just had to go about it a bit of a different way:
this is the important code:
int mykey = int.Parse(ProjectPhotosList.DataKeys[e.ItemIndex].Value.ToString());
its just a simple way to get the primarykey value of the selected row.
I found a post about uploading pdf's to a database and decided to base the rest of my code on that. So here the full code:
protected void ProjectPhotosList_ItemUpdating(object sender, ListViewUpdateEventArgs e)
{
FileUpload myFile = (FileUpload)ProjectPhotosList.EditItem.FindControl("uploadImage");
TextBox myCaption = (TextBox)ProjectPhotosList.EditItem.FindControl("ProjectPhotoCaptionTextBox");
int mykey = int.Parse(ProjectPhotosList.DataKeys[e.ItemIndex].Value.ToString());
if (myFile.HasFile)
{
//Get the posted file
Stream fileDataStream = myFile.PostedFile.InputStream;
//Get length of file
int fileLength = myFile.PostedFile.ContentLength;
//Create a byte array with file length
byte[] fileData = new byte[fileLength];
//Read the stream into the byte array
fileDataStream.Read(fileData, 0, fileLength);
//get the file type
string fileType = myFile.PostedFile.ContentType;
//Open Connection
PHJamesDataContext db = new PHJamesDataContext();
//Find the Right Row
PHJProjectPhoto Newphoto = (from p in db.PHJProjectPhotos
where p.ProjectPhotoId == mykey
select p).Single<PHJProjectPhoto>();
Newphoto.ProjectPhoto = fileData;
db.SubmitChanges();
}