图像是';t从MVC WCF服务向sql server数据库发送图像后显示在sql server数据库中
本文关键字:sql 数据库 server 图像 显示 服务 WCF MVC | 更新日期: 2023-09-27 17:59:13
我将图像从Windows Phone 8应用程序发送到MVC WCF服务。我知道它正在接收图像,因为当它确实接收到图像时,它会被指示将图像保存在一个名为"上传"的本地文件夹中。每次图像到达那里,它都会被放入这个文件夹中,这样我就可以判断它是上传的。我的问题是上传到我的SQL Server数据库。一切都可以编译,但当我检查数据库表时,它不在那里。请帮忙。
namespace MVCImageUpload.Controllers
{
public class FileUploadController : Controller
{
// GET: /FileUpload/
[HttpPost]
public ActionResult Index()
{
var fileUploaded = false;
foreach (string upload in Request.Files)
{
if (!HasFile(Request.Files[upload]))
continue;
string path = Path.Combine(
AppDomain.CurrentDomain.BaseDirectory,
"uploads");
string filename = Path.GetFileName(
Request.Files[upload].FileName);
if (!Directory.Exists(path))
Directory.CreateDirectory(path);
Request.Files[upload].SaveAs(Path.Combine(
path, filename));
fileUploaded = true;
updatedata(filename);
}
this.ViewData.Add("uploaded", fileUploaded);
return View();
}
private static bool HasFile(HttpPostedFileBase file)
{
return (file != null && file.ContentLength > 0) ? true : false;
}
private void updatedata(string imagename)
{
//use filestream object to read the image.
//read to the full length of image to a byte array.
//add this byte as an oracle parameter and insert it into database.
try
{
//proceed only when the image has a valid path
if (imagename != "")
{
FileStream fs;
fs = new FileStream(@imagename, FileMode.Open, FileAccess.Read);
//a byte array to read the image
byte[] picbyte = new byte[fs.Length];
fs.Read(picbyte, 0, System.Convert.ToInt32(fs.Length));
fs.Close();
//open the database using odp.net and insert the data
string connstr = @".'SQLEXPRESS;Database=ImageDB;Trusted_Connection=True;";
SqlConnection conn = new SqlConnection(connstr);
conn.Open();
string query;
query = "insert into Images(ActualImage) values(@ActualImage)";
SqlParameter picparameter = new SqlParameter();
picparameter.SqlDbType = SqlDbType.Image;
picparameter.ParameterName = "ActualImage";
picparameter.Value = picbyte;
SqlCommand cmd = new SqlCommand(query, conn);
cmd.Parameters.Add(picparameter);
cmd.ExecuteNonQuery();
//MessageBox.Show("Image Added");
cmd.Dispose();
conn.Close();
conn.Dispose();
//Connection();
}
}
catch (Exception ex)
{
//MessageBox.Show(ex.Message);
}
}
}
}
您可以跳过一个步骤,直接将文件保存到数据库中。
HttpPostedFileBase Picture = Request.Files["Picture"];
Byte[] Bytes = new byte[Picture.ContentLength];
string ContentType = Picture.ContentType;
string FileName = Picture.FileName;
Picture.InputStream.Read(Bytes, 0, Picture.ContentLength);
现在,您可以将名称、字节和内容类型存储在数据库中。