关于上传文件:
推荐使用插件Uploadify!
使用方法:http://www.uploadify.com/documentation/
下载地址:http://www.uploadify.com/download/
关于多图上传:
最后提交表达数据的时候就把这些路径集合保存到数据库即可!
通常对用户上传的图片需要保存到数据库中。解决方法一般有两种:一种是将图片保存的路径存储到数据库;另一种是将图片以二进制数据流的形式直接写入数据库字段中。以下为具体方法:一、保存图片的上传路径到数据库:
string uppath=""//用于保存图片上传路径
//获取上传图片的文件名
string fileFullname = this.FileUpload1.FileName
//获取图片上传的时间,以时间作为图片的名字可以防止图片重名
string dataName = DateTime.Now.ToString("yyyyMMddhhmmss")
//获取图片的文件名(不含扩展名)
string fileName = fileFullname.Substring(fileFullname.LastIndexOf("\\") + 1)
//获取图片扩展名
string type = fileFullname.Substring(fileFullname.LastIndexOf(".") + 1)
//判断是否为要求的格式
if (type == "bmp" || type == "jpg" || type == "jpeg" || type == "gif" || type == "JPG" || type == "JPEG" || type == "BMP" || type == "GIF")
{
//将图片上传到指定路径的文件夹
this.FileUpload1.SaveAs(Server.MapPath("~/upload") + "\\" + dataName + "." + type)
//将路径保存到变量,将该变量的值保存到数据库相应字段即可
uppath = "~/upload/" + dataName + "." + type
}
二、将图片以二进制数据流直接保存到数据库:
引用如下命名空间:
using System.Drawing
using System.IO
using System.Data.SqlClient
设计数据库时,表中相应的字段类型为iamge
保存:
//图片路径
string strPath = this.FileUpload1.PostedFile.FileName.ToString ()
//读取图片
FileStream fs = new System.IO.FileStream(strPath, FileMode.Open, FileAccess.Read)
BinaryReader br = new BinaryReader(fs)
byte[] photo = br.ReadBytes((int)fs.Length)
br.Close()
fs.Close()
//存入
SqlConnection myConn = new SqlConnection("Data Source=.Initial Catalog=stumanageUser ID=saPassword=123")
string strComm = " INSERT INTO stuInfo(stuid,stuimage) VALUES(107,@photoBinary )"// *** 作数据库语句根据需要修改
SqlCommand myComm = new SqlCommand(strComm, myConn)
myComm.Parameters.Add("@photoBinary", SqlDbType.Binary, photo.Length)
myComm.Parameters["@photoBinary"].Value = photo
myConn.Open()
if (myComm.ExecuteNonQuery() >0)
{
this.Label1.Text = "ok"
}
myConn.Close()
读取:
...连接数据库字符串省略
mycon.Open()
SqlCommand command = new
SqlCommand("select stuimage from stuInfo where stuid=107", mycon)//查询语句根据需要修改
byte[] image = (byte[])command.ExecuteScalar ()
//指定从数据库读取出来的图片的保存路径及名字
string strPath = "~/Upload/zhangsan.JPG"
string strPhotoPath = Server.MapPath(strPath)
//按上面的路径与名字保存图片文件
BinaryWriter bw = new BinaryWriter(File.Open(strPhotoPath,FileMode.OpenOrCreate))
bw.Write(image)
bw.Close()
//显示图片
this.Image1.ImageUrl = strPath
采用俩种方式可以根据实际需求灵活选择。
下面先介绍上传文件到服务器(多文件上传):import javax.servlet.*
import javax.servlet.http.*
import java.io.*
import java.util.*
import java.util.regex.*
import org.apache.commons.fileupload.*
public class upload extends HttpServlet {
private static final String CONTENT_TYPE = "text/htmlcharset=GB2312"
//Process the HTTP Post request
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType(CONTENT_TYPE)
PrintWriter out=response.getWriter()
try {
DiskFileUpload fu = new DiskFileUpload()
// 设置允许用户上传文件大小,单位:字节,这里设为2m
fu.setSizeMax(2*1024*1024)
// 设置最多只允许在内存中存储的数据,单位:字节
fu.setSizeThreshold(4096)
// 设置一旦文件大小超过getSizeThreshold()的值时数据存放在硬盘的目录
fu.setRepositoryPath("c://windows//temp")
//开始读取上传信息
List fileItems = fu.parseRequest(request)
// 依次处理每个上传的文件
Iterator iter = fileItems.iterator()
//正则匹配,过滤路径取文件名
String regExp=".+////(.+)$"
//过滤掉的文件类型
String[] errorType={".exe",".com",".cgi",".asp"}
Pattern p = Pattern.compile(regExp)
while (iter.hasNext()) {
FileItem item = (FileItem)iter.next()
//忽略其他不是文件域的所有表单信息
if (!item.isFormField()) {
String name = item.getName()
long size = item.getSize()
if((name==null||name.equals("")) &&size==0)
continue
Matcher m = p.matcher(name)
boolean result = m.find()
if (result){
for (int temp=0temp<ERRORTYPE.LENGTHTEMP++){
if (m.group(1).endsWith(errorType[temp])){
throw new IOException(name+": wrong type")
}
}
try{
//保存上传的文件到指定的目录
//在下文中上传文件至数据库时,将对这里改写
item.write(new File("d://" + m.group(1)))
out.print(name+" "+size+"")
}
catch(Exception e){
out.println(e)
}
}
else
{
throw new IOException("fail to upload")
}
}
}
}
catch (IOException e){
out.println(e)
}
catch (FileUploadException e){
out.println(e)
}
}
}
现在介绍上传文件到服务器,下面只写出相关代码:
以sql2000为例,表结构如下:
字段名:namefilecode
类型: varchar image
数据库插入代码为:PreparedStatement pstmt=conn.prepareStatement("insert into test values(?,?)")
代码如下:
。。。。。。
try{
这段代码如果不去掉,将一同写入到服务器中
//item.write(new File("d://" + m.group(1)))
int byteread=0
//读取输入流,也就是上传的文件内容
InputStream inStream=item.getInputStream()
pstmt.setString(1,m.group(1))
pstmt.setBinaryStream(2,inStream,(int)size)
pstmt.executeUpdate()
inStream.close()
out.println(name+" "+size+" ")
}
。。。。。。
这样就实现了上传文件至数据库
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)