javaweb上传图片
之前写过图片上传的案例,但是时间一长就忘了,这次写的这个程序用到了图片的上传,并且能够图文显示,所以写了这篇文章来记录一下。
首先来看下我的项目结构,我写的是房屋发布的信息,图片上传只是其中一部分,但是程序绝对是完整的
项目我是用Spring+SpringMVC+hibernate框架搭建的
先看下applicationContext-common.xml里面的文件配置:
<?xml version="1.0" encoding="UTF-8" ?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:p="http://www.springframework.org/schema/p" xmlns:util="http://www.springframework.org/schema/util"
xmlns:tool="http://www.springframework.org/schema/tool" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd http://www.springframework.org/schema/tool http://www.springframework.org/schema/tool/spring-tool.xsd"
default-lazy-init="false" default-autowire="byName">
<!-- 数据库链接配置 -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver">
</property>
<property name="url" value="jdbc:mysql://localhost:3306/sshkaoshi">
</property>
<property name="username" value="root"></property>
<property name="password" value="DCX5201314"></property>
</bean>
<!-- AnnotationSessionFactoryBean 注解才使用这个类 -->
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource">
<ref bean="dataSource" />
</property>
<!-- hibernate相关属性配置 -->
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.format_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<!--<prop key="hibernate.autocommit">true</prop> -->
</props>
</property>
<property name="packagesToScan">
<list>
<value>com.*</value>
</list>
</property>
</bean>
<!-- 配置事务3个步骤 1、配置事务管理器 2、配置拦截规则,需要选择事物管理器 3、配置拦截范围,需要选择拦截规则
-->
<!-- 1、事务管理器
-->
<bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<!-- 2、配置拦截规则
-->
<tx:advice id="txAdvice" transaction-manager="txManager">
<tx:attributes>
<tx:method name="get*" read-only="true" />
<tx:method name="find*" read-only="true" />
<tx:method name="load*" read-only="true" />
<tx:method name="add*" propagation="REQUIRED" />
<tx:method name="save*" propagation="REQUIRED" />
<tx:method name="update*" propagation="REQUIRED" />
<tx:method name="del*" propagation="REQUIRED" />
<tx:method name="*" propagation="REQUIRED" read-only="true" />
</tx:attributes>
</tx:advice>
<aop:config proxy-target-class="true">
<aop:pointcut expression="execution(* Service.*.*(..))"
id="serviceMethod" />
<aop:advisor advice-ref="txAdvice" pointcut-ref="serviceMethod" />
</aop:config>
<!-- 注解扫描包下的全部类文件 -->
<context:annotation-config />
<context:component-scan base-package="com.*"/>
</beans>
再看下springmvc-servlet.xml的配置文件:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:c="http://www.springframework.org/schema/c" xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:p="http://www.springframework.org/schema/p" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:util="http://www.springframework.org/schema/util" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
<!-- 配置handleMapping
<bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"/>
-->
<!-- 配置HandlerAdapter
<bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter"></bean>
-->
<!-- springmvc上传图片 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="utf-8"></property>
<property name="maxUploadSize" value="10485760000"></property>
<property name="maxInMemorySize" value="40960"></property>
</bean>
<!-- 用于将对象转为JSON -->
<bean id="stringConverter" class="org.springframework.http.converter.StringHttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>text/plain;charset=UTF-8</value>
</list>
</property>
</bean>
<bean id="jsonConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
</bean>
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<list>
<ref bean="stringConverter"/>
<ref bean="jsonConverter"/>
</list>
</property>
</bean>
<!-- 对模型视图添加前后缀
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:prefix="/WEB-INF/jsp/" p:suffix=".jsp"/>
-->
<!-- 注解 -->
<mvc:annotation-driven/>
<context:component-scan base-package="com.controller"/>
</beans>
再来看下工具包:
package com.until;
import java.io.PrintWriter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.alibaba.fastjson.JSON;
public class to_json{
/**
* 方法功能:将对象转换成JSON字符串,并响应回前台
* 参数:object
* 返回值:void
* 异常:IOException
*/
public static void writeJson(Object object,HttpServletRequest request,HttpServletResponse response) {
PrintWriter out = null;
try {
String json = JSON.toJSONStringWithDateFormat(object, "yyyy-MM-dd HH:mm:ss");
response.setContentType("text/html;charset=utf-8");
out = response.getWriter();
//System.out.println(json);
out.write(json);
out.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (out != null) {
out.close();
}
}
}
}
再看下要导入上传图片的jar包(框架的包我就不写了)主要是突出这个功能所以我把包单独建了一个文件:
下面再来到网页:fabu.jsp的文件
<body>
<DIV id=header class=wrap>
<DIV id=logo>
<IMG src="images/logo.gif">
</DIV>
</DIV>
<form action="fw/addfw.action" enctype="multipart/form-data" method="post">
<DIV id=regLogin class=wrap>
<DIV class=dialog>
<DL class=clearfix>
<DT>
新房屋信息发布
</DT>
<DD class=past>
填写房屋信息
</DD>
</DL>
<DIV class=box>
<DIV class=infos>
<TABLE class=field>
<TBODY>
<TR>
<TD class=field>
标 题:
</TD>
<TD>
<INPUT id="title" class=text type=text name="title">
</TD>
</TR>
<TR>
<TD class=field>
户 型:
</TD>
<TD>
<SELECT class=text name=type_id>
<OPTION selected value=1000>
一室一厅
</OPTION>
</SELECT>
</TD>
</TR>
<TR>
<TD class=field>
面 积:
</TD>
<TD>
<INPUT id="floorage" class=text type=text
name="floorage">
</TD>
</TR>
<TR>
<TD class=field>
价 格:
</TD>
<TD>
<INPUT id="price" class=text type=text
name="price">
</TD>
</TR>
<TR>
<TD class=field>
房产证日期:
</TD>
<TD>
<INPUT id="houseDate" class=text type=text
name="houseDate">
</TD>
</TR>
<TR>
<TD class=field>
位 置:
</TD>
<TD>
区:
<SELECT class=text name=district_id>
<OPTION selected value=1004>
海淀区
</OPTION>
</SELECT>
街:
<SELECT class=text name=street_id>
<OPTION selected value=1001>
中关村大街
</OPTION>
</SELECT>
</TD>
</TR>
<TR>
<TD class=field>
上传图片:
</TD>
<TD>
<INPUT id="file" class=text type=file
name="file">
</TD>
</TR>
<TR>
<TD class=field>
联系方式:
</TD>
<TD>
<INPUT id="contact" class=text type=text
name="contact">
</TD>
</TR>
<TR>
<TD class=field>
详细信息:
</TD>
<TD>
<TEXTAREA id="description" name="description"></TEXTAREA>
</TD>
</TR>
</TBODY>
</TABLE>
<DIV class=buttons>
<input type="submit" value="发布信息"/>
</form>
</DIV>
</DIV>
</DIV>
</DIV>
</DIV>
<DIV id=footer class=wrap>
<DL>
<DT>
京ICP证1000001号
</DT>
<DD>
关于我们 · 联系方式 · 意见反馈 · 帮助中心
</DD>
</DL>
</DIV>
</body>
因为图片上传需要用到表单提交,所以就没有用ajex提交了。
再来看看展示的list.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
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 'list.jsp' starting page</title>
<script type="text/javascript" src="jquery-1.8.0.min.js">
</script>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<HTML xmlns="http://www.w3.org/1999/xhtml">
<head>
<TITLE>租房 - 首页</TITLE>
<LINK rel=stylesheet type=text/css href="css/style.css">
<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">
-->
<script type="text/javascript">
function selectHouse(){
$.ajax({
url : 'fw/selectfw.action',
type : 'post',
data : {},
dataType : 'json',
success : function(data) {
var t = "";
for ( var i = 0; i < data.length; i++) {
t += "<tr><td style='width:100px'><img src='http://localhost:8080/sshkaoshi2/upload/"
+ data[i].url
+ "' width='100' height='75' ></td><td><span style='margin-left:10px'>"
+ data[i].title
+ "</span></td><TD><DL><DT>面积:"
+ data[i].floorage
+ "</DT><DD>年限:"
+ data[i].houseDate
+ "<BR>价格:"
+ data[i].price
+ "</DD></DL></TD><TD class=house-type><LABEL class=ui-green><INPUT onclick=update(46) value='修 改' type=button name=search></LABEL></TD><TD class=house-price><LABEL class=ui-green><INPUT value='删 除' type=button name=search></LABEL></TD></tr> ";
}
$("#table").html(t);
},
error : function(data) {
}
});
}
</script>
</head>
<input type="text" id="aa"/>
<input type="text" id="bb"/>
<body onload="selectHouse()">
<DIV id=header class=wrap>
<DIV id=logo>
<IMG src="images/logo.gif">
</DIV>
</DIV>
<DIV id=navbar class=wrap>
<DL class="search clearfix">
<DT>
<UL>
<LI class=bold>
房屋信息
</LI>
<LI>
标题:
<INPUT class=text type=text name=title>
<LABEL class=ui-blue>
<INPUT onclick=doSearch() value=搜索房屋 type=button name=search>
</LABEL>
</LI>
</UL>
</DT>
<DD>
<UL>
<LI class=first>
价格
</LI>
<LI>
<SELECT name=price>
<OPTION selected value="">
不限
</OPTION>
<OPTION value=0-100>
100元以下
</OPTION>
<OPTION value=100-200>
100元—200元
</OPTION>
<OPTION value=200-1000000>
200元以上
</OPTION>
</SELECT>
</LI>
</UL>
</DD>
<DD>
<UL>
<LI class=first>
房屋位置
</LI>
<LI>
<SELECT id=street name=street_id>
<OPTION selected value="">
不限
</OPTION>
<OPTION value=1000>
知春路
</OPTION>
<OPTION value=1001>
中关村大街
</OPTION>
<OPTION value=1002>
学院路
</OPTION>
<OPTION value=1003>
朝阳路
</OPTION>
</SELECT>
</LI>
</UL>
</DD>
<DD>
<UL>
<LI class=first>
房型
</LI>
<LI>
<SELECT name=type_id>
<OPTION selected value="">
不限
</OPTION>
<OPTION value=1000>
一室一厅
</OPTION>
<OPTION value=1001>
一室两厅
</OPTION>
<OPTION value=1002>
两室一厅
</OPTION>
<OPTION value=1003>
两室两厅
</OPTION>
</SELECT>
</LI>
</UL>
</DD>
<DD>
<UL>
<LI class=first>
面积
</LI>
<LI>
<SELECT name=floorage>
<OPTION selected value="">
不限
</OPTION>
<OPTION value=0-40>
40以下
</OPTION>
<OPTION value=40-500>
40-500
</OPTION>
<OPTION value=500-1000000>
500以上
</OPTION>
</SELECT>
</LI>
</UL>
</DD>
</DL>
</DIV>
<DIV class="main wrap">
<TABLE class=house-list id="table">
</TABLE>
<input type="button" value="显示所有的房屋信息" onclick="selectHouse()" />
<DIV class=pager>
<UL>
<LI class=current>
<A onclick="shouye()">首页</A>
</LI>
<LI>
<A onclick="shangye()">上一页</A>
</LI>
<LI>
<A onclick="xiaye()">下一页</A>
</LI>
<LI>
<A onclick="moye()">末页</A>
</LI>
</UL>
<SPAN class=total>1/2页</SPAN>
</DIV>
</DIV>
<DIV id=footer class=wrap>
<DL>
<DT>
京ICP证1000001号
</DT>
<DD>
关于我们 · 联系方式 · 意见反馈 · 帮助中心
</DD>
</DL>
</DIV>
</body>
</html>
再来看看controller层:
代码如下:
package com.controller;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import com.entity.fw;
import com.entity.json;
import com.service.fwService;
import com.until.to_json;
@Controller
@RequestMapping("fw")
public class fwController {
@Autowired
private fwService fs;
public fwService getFs() {
return fs;
}
public void setFs(fwService fs) {
this.fs = fs;
}
/*******************开始添加房屋信息******************************/
@SuppressWarnings("deprecation")
@RequestMapping("/addfw")
@ResponseBody
public void infor_insert(@RequestParam("file")CommonsMultipartFile file,HttpServletRequest request,HttpServletResponse response,fw f){
try {
String url = request.getRealPath("/upload");
System.out.println(url);
InputStream is1 = file.getInputStream();
OutputStream os = new FileOutputStream(new File(url, file
.getOriginalFilename()));
String path = file.getOriginalFilename();
System.out.println(path);
f.setUrl(path);
fs.addfw(f);
int length = 0;
byte[] buffer = new byte[400];
while ((length = is1.read(buffer)) != -1) {
os.write(buffer, 0, length);
}
os.close();
is1.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
response.sendRedirect("../list.jsp");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/***********************开始查询所有房屋*************************************/
@RequestMapping("/selectfw")
@ResponseBody
public void selectfw(HttpServletRequest request,HttpServletResponse response){
System.out.println("asda");
List<Map<String, Object>> list=new ArrayList<Map<String, Object>>();
try {
list=fs.selectfw();
} catch (Exception e) {
e.printStackTrace();
}
to_json.writeJson(list, request, response);
}
@RequestMapping("/fenye")
@ResponseBody
public void fenye(HttpServletResponse response,HttpServletRequest request,int page){
System.out.println("come in");
List<Map<String, Object>> list=new ArrayList<Map<String, Object>>();
list=fs.selectall();
int pages=list.size()%5==0?list.size()/5:list.size()/5+1;//计算总页数
if(page==0){
page=1;
}
List<Map<String, Object>> list1=fs.count(page);
System.out.println(list1.get(0));
json json=new json();
json.setList(list1);
json.setPage(page);
json.setPages(pages);
to_json.writeJson(json, request, response);
}
}
再来service层:
接口层代码:
package com.service;
import java.util.List;
import java.util.Map;
import com.entity.fw;
public interface fwService {
public int addfw(fw f);
public List<Map<String, Object>> selectfw();
public List<Map<String, Object>> count(int page);
public List<Map<String, Object>> selectall();
}
实现层代码:
package com.service.imp;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.dao.fwDao;
import com.entity.fw;
import com.service.fwService;
@Service("fwservice")
public class fwServiceImp implements fwService{
@Autowired
private fwDao fd;
public fwDao getFd() {
return fd;
}
public void setFd(fwDao fd) {
this.fd = fd;
}
/**************添加房屋*************************/
public int addfw(fw f) {
System.out.println("asd");
int a=fd.addfw(f);
if(a>0){
System.out.println("添加房屋成功");
}
return a;
}
/************查询所有房屋********************************/
public List<Map<String, Object>> selectfw() {
String sql="select *from fw ";
List<Map<String, Object>> list=fd.selectfw(sql);
return list;
}
public List<Map<String, Object>> count(int page) {
String sql="select * from fw";
List<Map<String, Object>> list=fd.count(sql,page);
return list;
}
public List<Map<String, Object>> selectall() {
String sql="select * from fw";
List<Map<String, Object>> list=fd.selectall(sql);
return list;
}
}
再来到dao层
接口层程序为:
package com.dao;
import java.util.List;
import java.util.Map;
import com.entity.fw;
public interface fwDao {
public int addfw(fw f);
public List<Map<String, Object>> selectfw(String sql);
public List<Map<String, Object>> count(String sql,int page);
public List<Map<String, Object>> selectall(String sql);
}
实现层程序:
package com.dao.imp;
import java.util.List;
import java.util.Map;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.transform.Transformers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.dao.fwDao;
import com.entity.fw;
@Repository("fwDao")
public class fwDaoImp implements fwDao{
@Autowired
private SessionFactory sessionFactory;
public SessionFactory getSessionFactory() {
return sessionFactory;
}
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
public Session getCurrentSession() {
return sessionFactory.openSession();//如果开启事务,要与事务配置的命名规则相符合
}
/************************添加房屋*****************************************/
public int addfw(fw f) {
System.out.println("来到dao层");
getCurrentSession().save(f);
int a=1;
return a;
}
/*************************查询房屋******************************************/
@SuppressWarnings("unchecked")
public List<Map<String, Object>> selectfw(String sql) {
Query query=getCurrentSession().createSQLQuery(sql);
query.setMaxResults(5);//显示当前最大行数
query.setFirstResult(0);//起始行数
List<Map<String, Object>> list=query.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).list();
return list;
}
@SuppressWarnings("unchecked")
public List<Map<String, Object>> count(String sql,int page) {
Query query=getCurrentSession().createSQLQuery(sql);
query.setMaxResults(5);
query.setFirstResult((page-1)*5);
List<Map<String, Object>> list=query.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).list();
return list;
}
@SuppressWarnings("unchecked")
public List<Map<String, Object>> selectall(String sql) {
Query query=getCurrentSession().createSQLQuery(sql);
List<Map<String, Object>> list=query.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).list();
return list;
}
}
接下来再来看看实体:
fw.java字段:
package com.entity;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
@Entity
public class fw {
private int fwid;
private String title;
private String floorage;
private String price;
private String houseDate;
private String contact;
private String description;
private String url;
@Id
@GeneratedValue
public int getFwid() {
return fwid;
}
public void setFwid(int fwid) {
this.fwid = fwid;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getFloorage() {
return floorage;
}
public void setFloorage(String floorage) {
this.floorage = floorage;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
public String getHouseDate() {
return houseDate;
}
public void setHouseDate(String houseDate) {
this.houseDate = houseDate;
}
public String getContact() {
return contact;
}
public void setContact(String contact) {
this.contact = contact;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
}
这是发布的界面
展示的界面:
数据库看看:
好了今天的程序就到这,这也是为了做个笔记,欢迎大家一起讨论。
----------------------------------------------------------------------------分割线--------------------------------------------------------------------------------------------
2021年9月9日更新记录
在orcle数据库中采用二进制保存图片时候,字段类型为BLOB的时候,对应实体应该采用
private byte pcbFile[];
byte的字段类型