日期:2014-05-18  浏览次数:20523 次

图片上传如何获取它的相对路径?


图片上传如何获取它的相对路径?



图片上传到服务器之后,获取它的相对路径之后写入到数据库wyx_info表里的wyx_img列

因为我想弄一个产品发布系统,肯定要上传产品的图片,将来前台显示产品时要调用图片的路径,所以只能是相对的

下面是一个简单的图片上传页面,现在传入表里的是服务器端路径,也就是进入数据库里成了“f:\**\01.jpg”等


问题一:

图片上传如何获取它的相对路径?


问题二:

如何让上传的图片以年月日的形式自动命名?因为考虑到实际应用当中有很多的产品图片是中文,所以必须在上传时进行自动转化





前台代码:

  <form id="form1" runat="server">
  <div>
  <br />
  <asp:FileUpload ID="FileUpload1" runat="server" /><br />
  &nbsp;<br />
  <br />
  <asp:Label ID="Label1" runat="server"></asp:Label><br />
  <br />
  <asp:Button ID="button1" runat="server" Text="确定" OnClick="button1_Click" />&nbsp;</div>
  </form>


后台代码:


  protected void Page_Load(object sender, EventArgs e)
  {

  }
  protected void button1_Click(object sender, EventArgs e)
  {
  if (FileUpload1.HasFile)
  {
  string fileContentType = FileUpload1.PostedFile.ContentType;


  if (fileContentType == "image/bmp" || fileContentType == "image/gif" || fileContentType == "image/pjpeg")
  {
  string name = FileUpload1.PostedFile.FileName; // 客户端文件路径
  FileInfo file = new FileInfo(name);
  string fileName = file.Name; // 文件名称
  string webFilePath = Server.MapPath("upfile/" + fileName); // 服务器端文件路径


  if (!File.Exists(webFilePath))
  {
  try
  {
  FileUpload1.SaveAs(webFilePath); // 使用 SaveAs 方法保存文件
  Label1.Text = "提示:文件“" + fileName + "”成功上传,文件类型为:" + FileUpload1.PostedFile.ContentType + ",文件大小为:" + FileUpload1.PostedFile.ContentLength + "B";
  Socut.Data.ExecuteNonQuery("INSERT INTO wyx_info (wyx_img) VALUES ('"+webFilePath+"')"); 
  }
  catch (Exception ex)
  {
  Label1.Text = "提示:文件上传失败,失败原因:" + ex.Message;
  }
  }
  else
  {
  Label1.Text = "提示:文件已经存在,请重命名后上传";
  }
  }
  else
  {
  Response.Write("<script>alert('提示:文件类型不符')</script>");

  }
  }

  }

------解决方案--------------------
Q:图片上传如何获取它的相对路径?如何让上传的图片以年月日的形式自动命名?
A:

C# code

//上传的图片以年月日的形式自动命名,年月日的话会导致一天只能上传一个文件
string fileName = DateTime.Today.Year.ToString() + DateTime.Today.Month.ToString() + DateTime.Today.Day.ToString() + DateTime.Today.Hour.ToString() + DateTime.Today.Minute.ToString() + DateTime.Today.Second.ToString();


Socut.Data.ExecuteNonQuery("INSERT   INTO   wyx_info   (wyx_img)   VALUES   ('upfile\"+fileName+"')");

------解决方案-------------------