Hi to all i'm a beginner in asp.net fileUploader and i'm using blow code to upload:
The HTML:
<asp:FileUpload ID="FileUpload1" runat="server" AllowMultiple="true" />
<br />
<br />
<asp:Button ID="Button1" runat="server" Text="Upload Selected File(s)" />
JavaScript code:
$("#Button1").click(function (evt) {
var fileUpload = $("#FileUpload1").get(0);
var files = fileUpload.files;
var data = new FormData();
for (var i = 0; i < files.length; i++) {
data.append(files[i].name, files[i]);
}
var options = {};
options.url = "FileUploadHandler.ashx";
options.type = "POST";
options.data = data;
options.contentType = false;
options.processData = false;
options.success = function (result) { alert(result); };
options.error = function (err) { alert(err.toString()); };
and the handler code:
if (context.Request.Files.Count > 0)
{
HttpFileCollection files = context.Request.Files;
for (int i = 0; i < files.Count; i++)
{
HttpPostedFile file = files[i];
string fname = context.Server.MapPath("~/uploads/" + file.FileName);
file.SaveAs(fname);
}
}
context.Response.ContentType = "text/plain";
context.Response.Write("File(s) Uploaded Successfully!");
I have two problems the first it can't find upload file in the root of the web application and second is the page postback is there somebody that help me about solve my problems thank!
I was a little confused with jQuery-File-Upload myself, but after reviewing the plugin documentation I found what is needed for the plugin to work on Windows environment.
PROBLEM 1: FILE SAVING - regarding this issue, make sure that you are saving to a valid and previously created directory, and also that you have WRITE permissions to that directory.
PROBLEM 2: UPLOAD POSTBACK - You must setup your upload script to write the uploaded file, AND return a valid JSON response to the plugin, as defined on the plugin documentation: https://github.com/blueimp/jQuery-File-Upload/wiki/Setup#using-jquery-file-upload-ui-version-with-a-custom-server-side-upload-handler
if (context.Request.Files.Count > 0) {
HttpFileCollection files = context.Request.Files;
for (int i = 0; i < files.Count; i++) {
HttpPostedFile file = files[i];
string fname = context.Server.MapPath("~/uploads/" + file.FileName);
file.SaveAs(fname);
}
}
upload_response = '{"files":[{"name": ' + file.FileName + '","size":' file.FileSize + ',"url":"http:\/\/example.org\/files\/ + file.FileName + ",'
upload_response =+ '"thumbnailUrl": "http:\/\/example.org\/files\/thumbnail\/ + file.FileName + ","deleteUrl": "http:\/\/example.org\/files\/ + file.FileName + ",'
upload_response =+ '"deleteType": "DELETE"}]}"'
context.Response.ContentType = "application/json";
context.Response.Write( upload_response );
Please note that I also changed the ContentType to "application/json". The syntax of this code may not be complete, but the most important is to output these JSON fields required by the plugin.
Related
Im having some trouble finding a way to Upload a document to the database in varbinary(max) with ASP.Net Webpages 2 and I would also like to download it.
So far what i have is this below which supposed to upload a file to a directory on the website but it isn't doing anything. Any help would be great. Thanks
var fileName = "";
var fileSavePath = "";
int numFiles = Request.Files.Count;
int uploadedCount = 0;
for (int i = 0; i < numFiles; i++)
{
var uploadedFile = Request.Files[i];
if (uploadedFile.ContentLength > 0)
{
fileName = Path.GetFileName(uploadedFile.FileName);
fileSavePath = Server.MapPath("~/UploadedFiles/" +
fileName);
uploadedFile.SaveAs(fileSavePath);
uploadedCount++;
}
}
message = "File upload complete. Total files uploaded: " +
uploadedCount.ToString();
The following code goes at the top of the page where you have your file upload. Note that you should amend the table and field names according to your database. Also, you should ensure that the form that includes your upload control has the enctype attribute set to multipart/form-data:
#{
int id = 0;
var fileName = "";
var fileMime = "";
if (IsPost) {
var uploadedFile = Request.Files[0];
fileName = Path.GetFileName(uploadedFile.FileName);
if(fileName != String.Empty)
{
fileMime = uploadedFile.ContentType;
var fileStream = uploadedFile.InputStream;
var fileLength = uploadedFile.ContentLength;
byte[] fileContent = new byte[fileLength];
fileStream.Read(fileContent, 0, fileLength);
var db = Database.Open("FileUploading");
var sql = "INSERT INTO Files (FileName, FileContent, MimeType) VALUES (#0,#1,#2)";
db.Execute(sql, fileName, fileContent, fileMime);
}
}
}
To display a file from the database, you need a separate "handler" file that contains just this code:
#{
int id = 0;
if(Request["Id"].IsInt()){
id = Request["Id"].AsInt();
var db = Database.Open("FileUploading");
var sql = "Select * From Files Where FileId = #0";
var file = db.QuerySingle(sql, id);
if(file.MimeType.StartsWith("image/")){
Response.AddHeader("content-disposition", "inline; filename=" + file.FileName);
} else {
Response.AddHeader("content-disposition", "attachment; filename=" + file.FileName);
}
Response.ContentType = file.MimeType;
Response.BinaryWrite((byte[])file.FileContent);
}
}
This file is used as the src attribute for an image file or as the URL for a link to a file that should be downloaded such as a PDF or Word file. If you call this handler file "download.cshtml", the link for an image file saved in the database should look like this:
<img src="download.cshtml?Id=#id" alt="" />
where the Id parameter value is the id fo the file in the database. A download link looks like this:
Click Here
All of this has been taken from my article: http://www.mikesdotnetting.com/Article/148/Save-And-Retrieve-Files-From-a-Sql-Server-CE-Database-with-WebMatrix. The only difference between the article which features a SQL Compact database is that the data type for files in SQL CE is image as opposed to varbinary(max) in SQL Server.
based on your code..you are not uploading the image to the database. instead u're saving the image on your folder which is located in your root / UploadedFiles
to store the image in the database..you should use this code..
using (Stream fs = uploadedFile.PostedFile.InputStream)
{
using (BinaryReader br = new BinaryReader(fs))
{
byte[] bytes = br.ReadBytes((Int32)fs.Length);
string contentType = uploadedFile.PostedFile.ContentType;
SqlParameter[] arParams = new SqlParameter[2];
arParams[0] = new SqlParameter("#ID", SqlDbType.Int);
arParams[0].Value = 1; 'example
arParams[1] = new SqlParameter("#contentType", SqlDbType.Varchar(50));
arParams[1].Value = contentType;
arParams[2] = new SqlParameter("#document", SqlDbType.Varbinary(MAX));
arParams[2].Value = bytes;
SqlHelper.ExecuteNonQuery(SQLConn, CommandType.StoredProcedure, "Upload_Attachment", arParams);
}
}
I have a little asp.net program that in this program i could write and run commands of command prompt in my asp.net application An important part of this story is to run exe files with commands.
It is my code but dont run exe file for example where i write mspaint it dont open:
<pre lang="c#">
try
{
Process p = new Process();
p.StartInfo.CreateNoWindow = false;
p.StartInfo.FileName = c_path.Value = Encoding.Default.GetString(Convert.FromBase64String(c_path.Value));
c_text.Value = Encoding.Default.GetString(Convert.FromBase64String(c_text.Value));
p.StartInfo.Arguments = c_text.Value;
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardInput = true;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.RedirectStandardError = true;
p.Start();
string[] Uoc = new string[20];
for (int i = 1; Uoc.Length > i; i++)
{
Uoc[i] = p.StandardOutput.ReadLine();
Uoc[i] = Uoc[i].Replace("<", "<");
Uoc[i] = Uoc[i].Replace(">", ">");
Uoc[i] = Uoc[i].Replace("\r\n", "<br>");
}
string txt = "";
foreach (var item in Uoc)
{
txt += item + "<br />";
}
cmd_response.InnerHtml = "<hr width=\"100%\" noshade/><pre>" + txt + "";
cmd_response.Visible = true;
more.Visible = true;
}
catch (Exception error)
{
xseuB(error.Message);
}
</pre>
If you look at Task Manager and have it show processes for all users, you will see that the programs do run, but they are running under a different session. As a security precaution, the sessions are independent of each other. Programs in one session can not be interacted with by other sessions.
The asp.net upload control is uploading the file for first time in Ipad but not after that and not even showing any error
The code is as below
protected void UploadThisFile(FileUpload upload)
{
try
{
string folderpath = ConfigurationManager.AppSettings["BTCommDynamic"].ToString() + ConfigurationManager.AppSettings["Attachments"].ToString();
Guid fileguid = Guid.NewGuid();
string filename = fileguid + upload.FileName;
if (upload.HasFile && dtFiles != null)
{
DataRow drFileRow = dtFiles.NewRow();
drFileRow["FileName"] = upload.FileName;
string theFileName = Path.Combine(Server.MapPath(folderpath), filename);
string theFileName1 = Path.Combine(folderpath, filename);
//string theFileName = folderpath;
//to save the file in specified path
upload.SaveAs(theFileName);
drFileRow["FilePath"] = theFileName1;
double Filesize = (upload.FileContent.Length);
if (Filesize > 1024)
{
drFileRow["FileSize"] = (upload.FileContent.Length / 1024).ToString() + " KB";
}
else
{
drFileRow["FileSize"] = (upload.FileContent.Length).ToString() + " Bytes";
}
dtFiles.Rows.Add(drFileRow);
gvAttachment.DataSource = dtFiles;
gvAttachment.DataBind();
}
}
catch (Exception ex)
{
string message = Utility.GetExceptionMessage(ex.GetType().ToString(), ex.Message);
Display_Message(message);
}
}
Do you use firebug? There might be an error on a client side that prevents the work of your functionality.
Do you have any logic on your client side? Some kinda jquery/ajax calls?
I'm using "jquery.uploadify.js" in my website and this jquery uses an ashx file for uploading images into a folder. In the .ashx, i am using Session["FileNameNews"] for saving images name and i am empty my Session["FileNameNews"] at the beginning of my code. But when i uploading two or three or ... images, each time my Session["FileNameNews"] is empty. I do not want to be empty my session every time I upload a photo and i want the uploaded images to be displayed in a listbox of the parent .aspx page. Other means, i need to my session empty in start of uplaod and fill with images names in end of upload. I am able to upload multiple image at a time.
Does anyone have an idea? Please Help me.
Thank you.
.aspx page:
<script type = "text/javascript">
$(window).load(
function() {
$("#<%=FileUpload1.ClientID%>").fileUpload({
'uploader': 'scripts/uploader.swf',
'cancelImg': 'images/cancel.png',
'buttonText': 'Browse Files',
'script': 'Upload.ashx',
'folder': 'Temp',
'fileDesc': 'Image Files',
'fileExt': '*.jpg;*.jpeg;*.gif;*.png',
'multi': true,
'auto': false
});
}
);
</script>
Start Upload
|Clear
<div style = "padding:40px">
<asp:FileUpload ID="FileUpload1" runat="server" />
</div>
and Upload.ashx:
public class Upload : IHttpHandler, IRequiresSessionState {
public void ProcessRequest(HttpContext context)
{
context.Session["FileNameNews"] = "";
context.Response.ContentType = "text/plain";
context.Response.Expires = -1;
try
{
HttpPostedFile postedFile = context.Request.Files["Filedata"];
string savepath = "";
string tempPath = "";
tempPath = "Temp";//System.Configuration.ConfigurationManager.AppSettings["FolderPath"];
savepath = context.Server.MapPath(tempPath);
string filename = postedFile.FileName;
if (!Directory.Exists(savepath))
Directory.CreateDirectory(savepath);
string SitePath = context.Server.MapPath(context.Request.ApplicationPath) + #"\Temp\";
string SitePath1 = context.Server.MapPath(context.Request.ApplicationPath) + #"\WebImages\NewsImages\";
string FileN = SitePath + filename + "{---}" + context.Session["UserID"].ToString();
if ((File.Exists(SitePath + filename + "{---}" + context.Session["UserID"])) || (File.Exists(SitePath1 + filename)))
{
return;
}
else
{
postedFile.SaveAs(savepath + #"\" + filename);
postedFile.SaveAs(savepath + #"\" + filename + "{---}" + context.Session["UserID"]);
if (context.Session["FileNameNews"] == "") { context.Session["FileNameNews"] = filename; }
else { context.Session["FileNameNews"] = context.Session["FileNameNews"] + "," + filename; }
context.Response.Write(tempPath + "/" + filename);
context.Response.StatusCode = 200;
}
}
catch (Exception ex)
{
context.Response.Write("Error: " + ex.Message);
}
}
public bool IsReusable
{
get
{
return false;
}
}
}
If this ashx handler is the endpoint for your file upload ajax request, and you throw an exception, you will never see the error message from your try / catch. You are likely "swallowing" your exceptions. Drop the try / catch and examine the result status (or error message) using the debug tools in your browser.
I have a ASP.NET (.NET Framework 3.5) Application. Now, I have to place a Button on a aspx-Page with the fallowing functionality on click:
Ask the user for a file with Extension xls (OpenFileDialog)
Upload the selected file to a specific folder on the WebServer
How can I do this?
Thanks for your help.
Here is the code that can be used for file upload after checking certain file types.
protected void Upload_File() {
bool correctExtension = false;
if (FileUpload1.HasFile) {
string fileName = FileUpload1.PostedFile.FileName;
string fileExtension = Path.GetExtension(fileName).ToLower();
string[] extensionsAllowed = {".xls", ".docx", ".txt"};
for (int i = 0; i < extensionsAllowed.Length; i++) {
if (fileExtension == extensionsAllowed[i]) {
correctExtension = true;
}
}
if (correctExtension) {
try {
string fileSavePath = Server.MapPath("~/Files/");
FileUpload1.PostedFile.SaveAs(fileSavePath + fileName);
Label1.Text = "File successfully uploaded";
}
catch (Exception ex) {
Label1.Text = "Unable to upload file";
}
}
else {
Label1.Text = "File extension " + fileExtension + " is not allowed";
}
}
}
You should start with the ASP.NET FileUpload control. Here is a pretty good tutorial on how to complete this task.