java实现图片上传至服务器并显示,如何做?希望要具体的代码实现

作者&投稿:荤才 (若有异议请与网页底部的电邮联系)
你好!我在网上看到了这个问题! java实现图片上传至服务器并显示,如何做?希望要具体的代码实现~

代码就不写了,快下班了,说下设计想法吧。
1、上传图片。这一点和所有的上传文件一样,网上有好多例子的,自己找吧
2、将上传的图片的名字存到数据库中。
3、在JSP中读数据库,生成标记的地址

预览,不能简单的用,然后把地址赋给src的,会出现浏览器不兼容问题
用css滤镜,像下面
document.getElementById("previewImg").style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod='scale',src='" + o.value + "')";
至于如何上传,struts2很方便的

很简单。
可以手写IO读写(有点麻烦)。
怕麻烦的话使用FileUpload组件 在servlet里doPost嵌入一下代码
public void doPost(HttpServletRequest request,HttpServletResponse response)
throws ServletException,IOException{
response.setContentType("text/html;charset=gb2312");
PrintWriter out=response.getWriter();

//设置保存上传文件的目录
String uploadDir =getServletContext().getRealPath("/up");
System.out.println(uploadDir);
if (uploadDir == null)
{
out.println("无法访问存储目录!");
return;
}
//根据路径创建一个文件
File fUploadDir = new File(uploadDir);
if(!fUploadDir.exists()){
if(!fUploadDir.mkdir())//如果UP目录不存在 创建一个 不能创建输出...
{
out.println("无法创建存储目录!");
return;
}
}

if (!DiskFileUpload.isMultipartContent(request))
{
out.println("只能处理multipart/form-data类型的数据!");
return ;
}

DiskFileUpload fu = new DiskFileUpload();
//最多上传200M数据
fu.setSizeMax(1024 * 1024 * 200);
//超过1M的字段数据采用临时文件缓存
fu.setSizeThreshold(1024 * 1024);
//采用默认的临时文件存储位置
//fu.setRepositoryPath(...);
//设置上传的普通字段的名称和文件字段的文件名所采用的字符集编码
fu.setHeaderEncoding("gb2312");

//得到所有表单字段对象的集合
List fileItems = null;
try
{
fileItems = fu.parseRequest(request);//解析request对象中上传的文件

}
catch (FileUploadException e)
{
out.println("解析数据时出现如下问题:");
e.printStackTrace(out);
return;
}

//处理每个表单字段
Iterator i = fileItems.iterator();
while (i.hasNext())
{
FileItem fi = (FileItem) i.next();
if (fi.isFormField()){
String content = fi.getString("GB2312");
String fieldName = fi.getFieldName();
request.setAttribute(fieldName,content);
}else{
try
{
String pathSrc = fi.getName();
if(pathSrc.trim().equals("")){
continue;
}
int start = pathSrc.lastIndexOf('\\');
String fileName = pathSrc.substring(start + 1);
File pathDest = new File(uploadDir, fileName);

fi.write(pathDest);
String fieldName = fi.getFieldName();
request.setAttribute(fieldName, fileName);
}catch (Exception e){
out.println("存储文件时出现如下问题:");
e.printStackTrace(out);
return;
}
finally //总是立即删除保存表单字段内容的临时文件
{
fi.delete();
}

}
}
注意 JSP页面的form要加enctype="multipart/form-data" 属性, 提交的时候要向服务器说明一下 此页面包含文件。

如果 还是麻烦,干脆使用Struts 的上传组件 他对FileUpload又做了封装,使用起来更傻瓜化,很容易掌握。

-----------------------------
以上回答,如有不明白可以联系我。

有两种方法一是用上传的组建jspSmartUpload的Request,
还有一种不用组建,但在form表单中不能加入ENCTYPE= "multipart/form-data "
我给你的案例吧
建立后台数据库

if exists (select * from dbo.sysobjects
where id = object_id(N'[dbo].[p]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
drop table [dbo].[p]
GO
CREATE TABLE [dbo].[p] (

[picid] [int] IDENTITY (1, 1) NOT NULL ,

[picname] [varchar] (50) COLLATE Chinese_PRC_CI_AS NULL ,

[pic] [image] NULL

) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

GO

3.向数据库存储二进制图片

启动Dreamweaver MX后,新建一个JSP文件。其代码如下所示。

<%@ page contentType="text/html;charset=gb2312"%>

<%

String path = request.getContextPath();

String basePath = request.getScheme()+"://"+request.getServerName()
+":"+request.getServerPort()+path+"/";

%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>

<head>

<base href="<%=basePath%>">

<title>My JSP 'InputImage.jsp' starting page</title>

<meta http-equiv="pragma" content="no-cache">

<meta http-equiv="cache-control" content="no-cache">

<meta http-equiv="expires" content="0">

<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">

<meta http-equiv="description" content="This is my page">

<!--

<link rel="stylesheet" type="text/css" href="styles.css">

-->

</head>

<body>

<form action="testimage.jsp" method="POST"><br>

题目<input name="picname" type="text"><br>

图片<input name="pic" type="file"><br>

<input type="Submit" name="button1" value="提交"><br>

</form>

</body>

</html>

将此文件保存为InputImage.jsp文件,其中testimage.jsp文件是用来将图片数据存入数据库的,具体代码如下所示:

<%@ page contentType="text/html;charset=gb2312"%>

<%@ page import="java.sql.*" %>

<%@ page import="java.util.*"%>

<%@ page import="java.text.*"%>

<%@ page import="java.io.*"%>

<jsp:useBean id="conn" scope="page" class="dbconn.DBResult"/>

<%
String path = request.getContextPath();

String basePath = request.getScheme()+"://"+request.getServerName()+
":"+request.getServerPort()+path+"/";

%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>

<head>

<base href="<%=basePath%>">

<title>My JSP 'testimage.jsp' starting page</title>

<meta http-equiv="pragma" content="no-cache">

<meta http-equiv="cache-control" content="no-cache">

<meta http-equiv="expires" content="0">

<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">

<meta http-equiv="description" content="This is my page">

<!--

<link rel="stylesheet" type="text/css" href="styles.css">

-->

</head>

<body>

<%
request.setCharacterEncoding("gb2312");

//建立Statement对象

String picname=request.getParameter("picname");

String pic=request.getParameter("pic");

//获得所要显示图片的标题、存储路径、内容,并进行中文编码

FileInputStream str=new FileInputStream(pic);

String sql="insert into p(picname,pic) values(?,?)";

PreparedStatement pstmt=conn.getPreparedStatement(sql);

pstmt.setString(1,picname);

pstmt.setBinaryStream(2,str,str.available());

pstmt.execute();

//将数据存入数据库

out.println("Success,You Have Insert an Image Successfully");

%>

</body>

</html>

4. 网页中动态显示图片

接下来我们要编程从数据库中取出图片,其代码如下所示。

<%@ page contentType="text/html;charset=gb2312"%>

<%@ page import="java.sql.*" %>

<%@ page import="java.util.*"%>

<%@ page import="java.text.*"%>

<%@ page import="java.io.*"%>

<jsp:useBean id="conn" scope="page" class="dbconn.DBResult"/>

<%

String path = request.getContextPath();

String basePath = request.getScheme()+"://"+request.getServerName()+
":"+request.getServerPort()+path+"/";

%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>

<head>

<base href="<%=basePath%>">

<title>My JSP 'testimageout.jsp' starting page</title>

<meta http-equiv="pragma" content="no-cache">

<meta http-equiv="cache-control" content="no-cache">

<meta http-equiv="expires" content="0">

<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">

<meta http-equiv="description" content="This is my page">

<!--

<link rel="stylesheet" type="text/css" href="styles.css">

-->

</head>

<body>

<%

int id= Integer.parseInt(request.getParameter("picid"));

String sql = "select pic from p WHERE picid="+id;

ResultSet rs=conn.getResult(sql);

while(rs.next())

{

ServletOutputStream sout = response.getOutputStream();

//图片输出的输出流

InputStream in = rs.getBinaryStream(1);

byte b[] = new byte[0x7a120];

for(int i = in.read(b); i != -1;)

{
sout.write(b);

//将缓冲区的输入输出到页面

in.read(b);

}

sout.flush();

//输入完毕,清除缓冲

sout.close();

}

%>

</body>

</html>

将此文件保存为testimageout.jsp文件。下一步要做的工作就是使用HTML标记:

<%@ page contentType="text/html;charset=gb2312"%>

<%@ page import="java.sql.*" %>

<%@ page import="java.util.*"%>

<%@ page import="java.text.*"%>

<%@ page import="java.io.*"%>

<jsp:useBean id="conn" scope="page" class="dbconn.DBResult"/>

<%

String path = request.getContextPath();

String basePath = request.getScheme()+"://"+request.getServerName()+
":"+request.getServerPort()+path+"/";

%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>

<head>

<base href="<%=basePath%>">

<title>My JSP 'lookpic.jsp' starting page</title>

<meta http-equiv="pragma" content="no-cache">

<meta http-equiv="cache-control" content="no-cache">

<meta http-equiv="expires" content="0">

<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">

<meta http-equiv="description" content="This is my page">

<!--

<link rel="stylesheet" type="text/css" href="styles.css">

-->

</head>

<body>

<%

String sql = "select * from p";

ResultSet rs=conn.getResult(sql);

while(rs.next())

{

%>

<ccid_file values="testimageout" % />" width="100" height="100">

<br>

<%

}

rs.close();

%>

</body>

</html>

自己上apache找common-fileupload,此包可单独用,struts也把它整合了,官网上的例子简单明了,另外楼上那位的smartupload已经破产许久了...一上传大文件就卡死

第一步,在SQL-Server中创建表

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[picTable]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
drop table [dbo].[picTable]
GO

CREATE TABLE [dbo].[picTable] (
[id] [int] IDENTITY (1, 1) NOT NULL ,
[pic] [image] NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO

第二步:上传页面
<%@ page contentType="text/html; charset=GBK" %>
<html>
<head>
<title>
index
</title>
</head>
<body bgcolor="#ffffff">
<form action="saveit.jsp" enctype="multipart/form-data" method="POST">
<input type="file" name="image" size="20" maxlength="20"/><p>
<input type="submit" value="上传"/>
</form>
<br>
<a href="servlet3">显示图片</a>
</body>
</html>

3.保存图片的jsp
<%@ page contentType="text/html; charset=GBK" import="upload.*"%>
<html>
<head>
<title>
jsp1
</title>
</head>
<body bgcolor="#ffffff">
<%
db.addPic(pageContext,application,out);
out.println("图片添加成功!");
%>
<br>
<a href="index.jsp">返回继续添加</a>
</a>
</body>
</html>

调用一个JavaBean中的addpic方法

package upload;
import com.jspsmart.upload.*;
import javax.servlet.jsp.*;
import javax.servlet.*;
import java.io.*;
import javax.servlet.http.*;

import java.sql.*;
public class db {
private static Connection conn=null;
public db() {
}
public static void InitConnection(String dbName)
{

}
public static void addPic(PageContext pageContext,ServletContext application,JspWriter out) {
try
{
//将上传文件存入应用程序目录
SmartUpload su=new SmartUpload();
su.initialize(pageContext);
su.setMaxFileSize(5*1024*1024);
su.upload();//到服务器的内存
com.jspsmart.upload.File f=su.getFiles().getFile(0);
String filename=f.getFileName();
filename=application.getRealPath("/")+filename;
f.saveAs(filename);

//通过流方式,读取文件,存入数据库中
java.io.File file=new java.io.File(filename);
FileInputStream fis=new FileInputStream(file);

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String strCon="jdbc:odbc:pubs";
conn=DriverManager.getConnection(strCon,"sa","");
Statement st=conn.createStatement();
String sql="insert into picTable (pic,type) values(?,?)";
//预编译命令
PreparedStatement ps=conn.prepareStatement(sql);
ps.setBinaryStream(1,fis,(int)file.length());
ps.setString(2,filename.substring(filename.lastIndexOf(".")+1));
ps.executeUpdate();
//删除文件
fis.close();
boolean isOK=file.delete();
if(!isOK)
{
System.out.println("文件删除失败");
}
ps.close();
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
}
public static void display(HttpServletResponse response) throws Exception
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String strCon="jdbc:odbc:pubs";
conn=DriverManager.getConnection(strCon,"sa","");
Statement st=conn.createStatement();

//显示图片
String sql = "select [type],pic from picTable";
st=conn.createStatement();
ResultSet rs = st.executeQuery(sql);
response.reset();
while(rs.next())
{
String type = rs.getString(1);

//读取二进制流,将文件内容写入二进制文件
InputStream in = rs.getBinaryStream(2);
byte[] buffer =new byte[1444];
int byteread=0;
while ((byteread=in.read(buffer))!=-1)
{
response.getOutputStream().write(buffer,0,byteread);
}
}
response.getOutputStream().close();
rs.close();
}
}

显示图片调用display

Tip:记住别忘了导包:jspsmartupload 这个包。

用FCKEditor多好,一个插件搞定一系列需求


档案管理详细资料大全
能为企业或项目提供集中式的档案存储、上传和共享服务,特别适合企业建立自己专用的档案管理系统,是非结构化大数据和多媒体档案的存储管理的首选平台,实施该项目最大的价值在于取得企业运营最关键信息数据的控制权。 其他flickr、yupoo等线上图片管理网站,只能管理图片,不能管理其他类型的档案 工具 Windowns资源管理器 QT...

女孩起a字开头的英文名字女生取简单英文名
那a字开头的女生简单英文名有哪些呢?如果你还没有好的名字,不妨来看看小编介绍的这些。a字开头的女生简单英文名精选一般女生的英文名都比较好听,不喜欢太复杂的,简单点的更好。下面小编就给大家介绍一些a字开头的女生简单英文名。声明:图片由网友上传,来源网络,如有侵权,敬请告知删除!1、abbie ...

成华区13711832180: java如何实现上传图片到服务器,并预览图片 -
从风盐酸: 预览,不能简单的用<img>,然后把地址赋给src的,会出现浏览器不兼容问题 用css滤镜,像下面 document.getElementById("previewImg").style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod='scale',src='" + o.value + "')"; 至于如何上传,struts2很方便的

成华区13711832180: java实现图片上传至服务器并显示,如何做? -
从风盐酸: 给你段代码,是用来在ie上显示图片的(servlet):public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String id = request.getParameter("id"); File file = new File(...

成华区13711832180: java中怎么将本地图片上传到服务器上 -
从风盐酸: 服务器端,做一个FTP,客户端使用APACHE的FTP组件上传.......或 服务器端实现HTTP的POST接收,,,,,客户端使用httpclient组件post上去

成华区13711832180: java web开发,上传图片并读取 -
从风盐酸: java web开发中,使用文件操作类来上传图片并读取,如下代码: * @desc: 图片处理工具 * @author: bingye * @createTime: 2015-3-17 下午04:25:32 * @version: v1.0 */ public class ImageUtil { /** * 将图片写到客户端 * @author: bingye * @...

成华区13711832180: java 开发 做web 怎么给数据库放图片 然后要怎么才能把这图片显示在页面呢? -
从风盐酸: 一般不把图片存到数据库里,你用smartupload或者common-upload组件把图片传到服务器上,上传成功后把图片名称放到数据库里,显示的时候先...

成华区13711832180: JAVA 上传图片到服务器 -
从风盐酸: 你需需要明白,java数据通信,HTTP协议,TCP协议,UDP协议,你上面用的post、get就是HTTP协议的内容

成华区13711832180: 用jsp、java实现上传图片,保存到数据库,从数据库中提取,显示到页面 这四步
从风盐酸: 用上传组件将图片上传到服务器下的某个文件夹,路径和文件名保存到数据库中

成华区13711832180: java合成图片放到服务器 -
从风盐酸: 小鸟云服务器niaoyun实例创建好之后,您可以使用以下任意一种方式登录服务器:远程桌面连接(MicrosoftTerminalServicesClient,MSTSC):采用这种方式登录,请确保实例能访问公网.如果在创建实例时没有购买带宽,则不能使用远程桌...

成华区13711832180: java 如何只通过后台把本地的图片上传的服务器上去 -
从风盐酸: import java.io.*; public class CopyIMG{ public static void main(String[] args)throws Exception{ File file = new File("C:\\xx.jpg"); if(!file.exists()) throw new RuntimeException("文件不存在.."); FileInputStream fis = new FileInputStream(file); ...

成华区13711832180: java 怎么读取本地磁盘图片上传到服务器 -
从风盐酸: 可以使用 java.net.HttpURLConnection模拟上传,,,,也可以使用 apache的 HttpClient 模拟POST上传的 ~

本站内容来自于网友发表,不代表本站立场,仅表示其个人看法,不对其真实性、正确性、有效性作任何的担保
相关事宜请发邮件给我们
© 星空见康网