webmethod上传文件 [英] file upload by webmethod
问题描述
如果我使用任何文件上传控件(Asp或jquery),我想这样做 -
我有一个webmethod是通过保存按钮调用。我的代码用于将数据保存到数据库。现在我想在此webmethod中访问上传的文件名,以便我可以设置保存在数据库中的路径,然后我希望将文件上传到服务器文件夹。
我发现webhandeller的代码很好,文件正在上传到服务器文件夹,但我需要文件名,以便我可以在数据库中保存路径。
任何人都可以帮助我吗?
If I use any file upload control (of Asp or jquery),I want to do this like this way---
I have a webmethod which is called by save button.There is my code for saving data to database.Now I want to acess the uploaded file name in this webmethod so that I can set the path to save in database and then I want the file will be uploaded to server folder.
I have found a code by webhandeller which is good and files are uploading to server folder but I need the file names so that I can save the path in database.
Can anyone help me?
推荐答案
我是这样做的:
Here's how I do it:
/// <summary>
/// Save an upload into the database.
/// </summary>
/// <param name="fl">Control containing the download.</param>
/// <returns>Status as a string</returns>
private string SaveUpload(FileUpload fl)
{
if (fl.HasFile)
{
try
{
int version = 0;
string filename = Path.GetFileName(fl.FileName);
byte[] filedata = fl.FileBytes;
string strCon = ConnectionStrings.Download;
using (SqlConnection con = new SqlConnection(strCon))
{
con.Open();
// Check version - if the file exists in the DB already, then increase version number.
using (SqlCommand ver = new SqlCommand("SELECT MAX(version) FROM dlContent WHERE fileName=@FN", con))
{
ver.Parameters.AddWithValue("@FN", filename);
object o = ver.ExecuteScalar();
if (o != null && o != System.DBNull.Value)
{
// Exists already.
version = (int) o + 1;
}
}
// Stick file into database.
using (SqlCommand ins = new SqlCommand("INSERT INTO dlContent (iD, fileName, description, dataContent, version, uploadedOn) " +
"VALUES (@ID, @FN, @DS, @DT, @VS, @UD)", con))
{
ins.Parameters.AddWithValue("@ID", Guid.NewGuid());
ins.Parameters.AddWithValue("@FN", filename);
ins.Parameters.AddWithValue("@DS", "");
ins.Parameters.AddWithValue("@DT", filedata);
ins.Parameters.AddWithValue("@VS", version);
ins.Parameters.AddWithValue("@UD", DateTime.Now);
ins.ExecuteNonQuery();
}
}
return string.Format("{0} uploaded, version = {1}", filename, version);
}
catch (Exception ex)
{
return "The file could not be uploaded. The following error occured: " + ex.Message;
}
}
return "Please select a file.";
}
只需从保存按钮调用它并将上传控件传递给它。
Just call that from your save button and pass the upload control to it.
由我通过设置上传者的url属性使用处理程序完成。
Done by me using handler by setting url property of uploader.
这篇关于webmethod上传文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!