protected void Button1_Click(object sender, EventArgs e)
{
if (FileUploadControl.HasFile)
{
try
{
string filename = Path.GetFileName(FileUploadControl.FileName);
FileUploadControl.SaveAs(Server.MapPath("~/Files/") + filename);
StatusLabel.Text = "Upload status: File uploaded!";
String x = Server.MapPath("~/Files/") + filename;
}
catch (Exception ex)
{
StatusLabel.Text = "Upload status: The file could not be uploaded. The following error occured: " + ex.Message;
}
}
}
In this simple example, when I try file that is under 1MB, it works well, but if I try 10MB, i get "This site can’t be reached The connection was reset." Which is browser message.
So where's the problem?
Check your web.config file (10mb and 5 minutes):
<system.web>
<httpRuntime maxRequestLength="102400" executionTimeout="300"/>
</system.web>
Related
I am able to upload other file types to share point using the lines of code below. However, when I try to upload an uadio file I get an error that reads "The given path's format is not supported" on the line where it trys to create the directory and save the file on SharePoint. The line reads System.IO.Directory.CreateDirectory(pathString);
I am suspecting the backslashes in path below my be a problem
Path
public static string CMSdocs1drive = "\\\\myserver.sharepoint.com#SSL\\DavWWWRoot\\personal\\myname_myorganisation_org_com\\";
Code To Upload And Save To SharePoint
protected void btnUpload_Click(object sender, EventArgs e)
{
if (FileUpload_Section55_6.HasFile)
{
if (ddlDocument.SelectedIndex == 0)
{
Page.ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('" + "Upload status: Please select the document type." + "');", true);
}
else
{
try
{
if (FileUpload_Section55_6.PostedFile.ContentLength < 2014572800)
{
{
if (ddlFilingType.SelectedIndex != 0)
{
if (!String.IsNullOrEmpty(lblCaseID0.Text) && ddlDocument.SelectedValue.ToString() == "203")
pathString = CMSProperties.CMSdocs1drive + "\\" + lblCaseID0.Text + "\\" + ddlFilingType.SelectedItem.Text + "\\" + ".Mp3";
}
if (!Directory.Exists(pathString))
{
System.IO.Directory.CreateDirectory(pathString);
// System.IO.Directory.Move(pathString);
}
if (pathString != controller.CheckIfFilePathExist(pathString))
{
controller.UploadFile(pathString, lblCaseID.Text);
}
}
}
else
{
Page.ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('" + "Upload status: The file is to big!" + "');", true);
}
ddlDocument.SelectedIndex = 0;
}
catch (Exception ex)
{
ex.Message.ToString();
Page.ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('" + "Upload status: The file could not be uploaded. The following error occured:" + "');" + ex, true);
Console.WriteLine();
}
}
}
else
{
Page.ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('" + "Upload status: Please select file " + "');", true);
}
}
I am suspecting the backslashes in path below my be a problem
Consider using a Verbatim Operator( # ) for the path to denote that it contains escape sequence characters (the \ symbol) that should be ignored.
public static string CMSdocs1drive = "\\\\myserver.sharepoint.com#SSL\\DavWWWRoot\\personal\\myname_myorganisation_org_com\\";
with the verbatim operator you can avoid the use of additional escape sequence characters, for example:
public static string CMSdocs1drive = #"\\myserver.sharepoint.com#SSL\DavWWWRoot\personal\myname_myorganisation_org_com\";
I am trying to delete files from isolated storage. But it returning error message to me. I don't know where i did mistake.
public void Delete(string folder, string fileName)
{
try
{
string path = folder + "\\" + fileName + ".txt";
string delPath = folder + "/" + fileName + ".txt";
MessageBox.Show(delPath);
if (myIsolatedStorage.DirectoryExists(folder))
{
if (myIsolatedStorage.FileExists(delPath))
{
myIsolatedStorage.DeleteFile(delPath);
MessageBox.Show("File is Deleted..!!");
}
else
MessageBox.Show("There is no file is exists");
}
else
{
MessageBox.Show("There is no Folder is exists");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
Please let me know where i did mistake.
Thanks in advance..
Error message:-
Perhaps, the file, you're trying to delete, is still in usage. Your application should have no open files or references to files that you are trying to delete.
I have a simple program here wherein I can create a folder then save the an image to the folder created. The folder gets successfully created but I'm getting error into saving it to the newly created file. The error is:
The file could not be uploaded. The following error occured: 'N:/Kim's New Project/Safety Accident Report/File Uploader 2/File
Uploader 2/Uploads/asdsa' is a physical path, but a virtual path was
expected.
Can you please check my code. Please help. Thank you.
protected void button1_Click(object sender, EventArgs e)
{
if (FileUpload2.HasFile)
{
try
{
if (FileUpload2.PostedFile.ContentType == "image/jpeg")
{
if (FileUpload2.PostedFile.ContentLength < 512000)
{
string strpath = #"N:\Kim's New Project\Safety Accident Report\File Uploader 2\File Uploader 2\Uploads\" + txtName.Text;
if (!(Directory.Exists(strpath)))
{
Directory.CreateDirectory(strpath);
lblResult.Text = "Directory Created";
if ((Directory.Exists(strpath)))
{
string filename = Path.GetFileName(FileUpload2.FileName);
FileUpload2.SaveAs(Server.MapPath(strpath) + filename);
Label1.Text = "File uploaded successfully!";
}
}
else
{
lblResult.Text = "Already Directory Exists with the same name";
}
}
else
Label1.Text = "File maximum size is 500 Kb";
}
else
Label1.Text = "Only JPEG files are accepted!";
}
catch (Exception exc)
{
Label1.Text = "The file could not be uploaded. The following error occured: " + exc.Message;
}
}
Instead of
FileUpload2.SaveAs(Server.MapPath(strpath) + filename);
try
FileUpload2.SaveAs(Path.Combine(strPath, filename));
you already know the physical save path - no need for Server.MapPath
Try..
string strpath = Server.MapPath("~/Test");
if (!(Directory.Exists(strpath)))
{
Directory.CreateDirectory(strpath);
}
I wrote the code to upload the file and save in project root directory. How can I change this to save the path into database and the files into a separate folder from project?
protected void UploadButton_Click(object sender, EventArgs e)
{
if(FileUploadControl.HasFile)
{
try
{
string filename = Path.GetFileName(FileUploadControl.FileName);
FileUploadControl.SaveAs(Server.MapPath("~/") + filename);
StatusLabel.Text = "Upload status: File uploaded!";
}
catch(Exception ex)
{
StatusLabel.Text = "Upload status: The file could not be uploaded. The following error occured: " + ex.Message;
}
}
}
protected void UploadButton_Click(object sender, EventArgs e)
{
if (FileUploadControl.HasFile) {
try {
string filename = Path.GetFileName(FileUploadControl.FileName);
FileUploadControl.SaveAs(Server.MapPath("~/") + filename);
saveImgPathToDB(filename, 3);
StatusLabel.Text = "Upload status: File uploaded!";
} catch (Exception ex) {
StatusLabel.Text = "Upload status: The file could not be uploaded. The following error occured: " + ex.Message;
}
}
}
private void saveImgPathToDB(string path, int recordID)
{
using (sqlconnection db = new sqlconnection("your_connection_string")) {
using (sqlcommand cmd = new sqlcommand("INSERT INTO photo_table (PhotoPath) VALUES (#path) WHERE someId=#someid", cn)) {
cmd.parameters.addwithvalue("#path", path);
cmd.parameters.addwithvalue("someid", recordID);
cmd.connection.open();
try {
cmd.executenonquery();
}
}
}
}
I get the problem newline in constant:
protected void UploadButton_Click(object sender, EventArgs e)
{
string theUserId = Session["UserID"].ToString();
if (FileUploadControl.HasFile)
{
try
{
string filename = Path.GetFileName(FileUploadControl.FileName);
FileUploadControl.SaveAs(Server.MapPath("~/userdata/"+theUserId+"/uploadedimage/) + filename);
//here
StatusLabel.Text = "Upload status: File uploaded!";
}
catch (Exception ex)
{
StatusLabel.Text = "Upload status: The file could not be uploaded. The following error occured: " + ex.Message;
}
}
}
}
Im also wondering is there a way I can resize the image upon upload if so, how?
And as this is a save as in my fileupload control will this overwrite any folder that has the userid already there? (what I want and need)
Newline in constant
FileUploadControl.SaveAs(Server.MapPath("~/userdata/"+theUserId+"/uploadedimage/) + filename);
//here
Should be:
FileUploadControl.SaveAs(Server.MapPath("~/userdata/"+theUserId+"/uploadedimage/") + filename);
//here
Image resize / thumbnails
If it's a thumbnail image you're after, then you can use Image.GetThumbnailImage. A basic implementation is like this:
using (System.Drawing.Image fullsizeImage =
System.Drawing.Image.FromFile(originalFilePath))
{
// these calls to RotateFlip aren't essential, but they prevent the image
// from using its built-in thumbnail, which is invariably poor quality.
// I like to think of it as shaking the thumbnail out ;)
fullsizeImage.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone);
fullsizeImage.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone);
using (System.Drawing.Image thumbnailImage =
fullsizeImage.GetThumbnailImage(newWidth, newHeight, null, IntPtr.Zero))
{
thumbnailImage.Save(newFilePath);
}
}
Overwrite
Overwrite is the default behaviour, so uploading the same file to the same UserID will replace it.
Well I can already see in the line above your error you are missing a quote after /uploadedimage/ and the next to last paren should be after filename not /uploadedimage/
Are you missing a quote or is it a typo:
Server.MapPath("~/userdata/"+theUserId+"/uploadedimage/")
I would also recommend using string.Format when using lots of string concatenation (usually do this when I have to use + more than once):
Server.MapPath(string.Format("~/userdata/{0}/uploadedimage/", theUserId))
EDIT: to answer resize comment:
Here is a link to a similar SO question:
how to resize an image whileing saving in an folder
Which value has the newline variable?
Below adds a Trim() to the value collected and also provides a way to see what each of the string values collected afterwards are.
protected void UploadButton_Click(object sender, EventArgs e)
{
string theUserId = Session["UserID"].ToString().Trim(); // add Trim()
if (FileUploadControl.HasFile && !String.IsNullOrEmpty(theUserId)) // add test
{
try
{
string filename = Path.GetFileName(FileUploadControl.FileName);
Console.WriteLine(filename);
string filepath = string.Format("~/userdata/{0}/uploadedimage/", theUserId);
Console.WriteLine(filepath );
string mapPath = Server.MapPath(filepath);
Console.WriteLine(mapPath );
FileUploadControl.SaveAs(mapPath + filename);
StatusLabel.Text = "Upload status: File uploaded!";
}
catch (Exception ex)
{
StatusLabel.Text = "Upload status: The file could not be uploaded. The following error occured: " + ex.Message;
}
}
}
Just Trim() the string value has the newline constant in it.