【I/O操作】 Struts框架下上传图片

    从事开发的人一定会碰到对不同文件的上传和下载功能,项目中用到了上传图片并预览的功能,总结一下分享给大家。

框架:Struts 2

数据库:MySQL

前台:servlet

效果图如下:

    

servlet页面代码清单:

<%@page import="com.bjpowernode.drp.basedata.domain.Item"%>
<%@ page language="java" contentType="text/html; charset=GB18030"
	pageEncoding="GB18030"%>

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

	Item item = (Item) request.getAttribute("item");
%>
<html>
<head>
<base href="<%=basePath%>">
<title>物料维护</title>
<link rel="stylesheet" href="style/drp.css">
<script src="script/client_validate.js"></script>
<script language="javascript">
	
</script>
</head>

<body class="body1">
	<form name="itemForm" target="_self" id="itemForm"
		action="servlet/item/FileUploadServlet" enctype="multipart/form-data"
		method="post">
		<input type="hidden" name="itemNo" value="<%=item.getItemNo()%>">
		<div align="center">
			<table width="95%" border="0" cellspacing="2" cellpadding="2">
				<tr>
					<td> </td>
				</tr>
			</table>
			<table width="95%" border="0" cellspacing="0" cellpadding="0"
				height="8">
				<tr>
					<td width="522" class="p1" height="2" nowrap><img
						src="images/mark_arrow_03.gif" width="14" height="14">
						  <b>基础数据管理>>物料维护>>上传物料图片</b></td>
				</tr>
			</table>
			<hr width="97%" align="center" size=0>
			<table width="95%" border="0" cellpadding="0" cellspacing="0">
				
				<tr>
					<td height="74">
						<div align="right">图片: </div>
					</td>
<span style="white-space:pre">					<!-- 加载图片 --></span>
					<td><img src="upload/<%=item.getFileName()%>" width="85"
						height="49"></td>
				</tr>
				<tr>
					<td width="20%" height="150">
						<div align="right">
							<font color="#FF0000">*</font>选择图片: 
						</div>
					</td>
					<td width="78%"><input name="fileName" type="file"
						class="text1" size="40" maxlength="40"></td>
				</tr>
			</table>
			<hr width="97%" align="center" size=0>
			<div align="center">
				<input name="btn_upload" class="button1" type="submit"
					id="btn_upload" value="上传">      <input
					name="btnBack" class="button1" type="button" id="btnBack"
					value="返回" onClick="history.go(-1)">
			</div>
		</div>
	</form>
</body>
</html>
核心java类清单:

package com.bjpowernode.drp.basedata.web;

import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.bjpowernode.drp.basedata.manager.ItemManager;
import com.bjpowernode.drp.basedata.manager.ItemManagerImpl;
import com.bjpowernode.drp.util.ApplicationException;

//public class FileUploadServlet extends HttpServlet {
//	private ItemManager itemManager; 

public class FileUploadServlet extends AbstractItemServlet {

	private File uploadPath;

	private File tempPath;

	private ItemManager itemManager;

	public void doPost(HttpServletRequest req, HttpServletResponse res)
			throws ServletException, IOException {
		// form提交采用multipart/form-data,无法采用req.getParameter()取得数据
		DiskFileItemFactory factory = new DiskFileItemFactory();
		// maximum size that will be stored in memory
		factory.setSizeThreshold(4096);
		// the location for saving data that is larger than getSizeThreshold()
		factory.setRepository(tempPath);

		ServletFileUpload upload = new ServletFileUpload(factory);
		// maximum size before a FileUploadException will be thrown
		upload.setSizeMax(1000000 * 20);
		try {
			List fileItems = upload.parseRequest(req);
			String itemNo = "";
			for (Iterator iter = fileItems.iterator(); iter.hasNext();) {
				FileItem item = (FileItem) iter.next();

				// 是普通的表单输入域
				if (item.isFormField()) {
					if ("itemNo".equals(item.getFieldName())) {
						itemNo = item.getString();
					}
				}
				// 是否为input="type"输入域
				if (!item.isFormField()) {
					String fileName = item.getName();
					long size = item.getSize();
					if ((fileName == null || fileName.equals("")) && size == 0) {
						continue;
					}
					// 截取字符串 如:C:\WINDOWS\Debug\PASSWD.LOG
					fileName = fileName.substring(
							fileName.lastIndexOf("\\") + 1, fileName.length());
					// item.write(new File(uploadPath, itemNo + ".gif"));
					item.write(new File(uploadPath, fileName));
					itemManager.uploadItemImage(itemNo, fileName);
				}
			}
			res.sendRedirect(req.getContextPath()
					+ "/servlet/item/SearchItemServlet");
		} catch (Exception e) {
			e.printStackTrace();
			throw new ApplicationException("上传失败!");
		}
	}

	public void init() throws ServletException {
		itemManager = new ItemManagerImpl();
		// 取得upload的绝对路径
		uploadPath = new File(getServletContext().getRealPath("upload"));
		System.out.println("uploadPath=====" + uploadPath);
		// 如果目录不存在
		if (!uploadPath.exists()) {
			// 创建目录
			uploadPath.mkdir();
		}

		// 临时目录
		tempPath = new File(getServletContext().getRealPath("temp"));
		if (!tempPath.exists()) {
			tempPath.mkdir();
		}
		// 显示调用父类的init方法
		super.init();
	}
}

    该工具类会将上传的文件保存在服务器所在路径下的upload文件夹下。这里用到了private ItemManager itemManager这个后台方法,具体的业务逻辑就是将前台拿到的数据传递过去完成在数据库中的更新,需要提出的是这里对图片的保存仅仅是一个图片的文件名字,由于关系型数据库MySQL的限制,并没有将其原件保存下来(之后还会介绍一下非关系型数据库中该功能的实现方式,敬请期待!),相应的当显示的时候就从upload路径下取得图片加载。

web.xml配置文件清单:

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee 
	http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

	<filter>
		<filter-name>CharsetEncodingFilter</filter-name>
		<filter-class>com.bjpowernode.drp.util.filter.CharsetEncodingFilter</filter-class>
		<init-param>
			<param-name>encoding</param-name>
			<param-value>GBK</param-value>
		</init-param>
	</filter>

	<filter-mapping>
		<filter-name>CharsetEncodingFilter</filter-name>
		<url-pattern>*.jsp</url-pattern>
	</filter-mapping>

	<filter-mapping>
		<filter-name>CharsetEncodingFilter</filter-name>
		<url-pattern>/servlet/*</url-pattern>
	</filter-mapping>

	<session-config>
		<session-timeout>60</session-timeout>
	</session-config>

	<servlet>
		<servlet-name>FileUploadServlet</servlet-name>
		<servlet-class>com.bjpowernode.drp.basedata.web.FileUploadServlet</servlet-class>
		<load-on-startup>10</load-on-startup>
	</servlet>

	<servlet-mapping>
		<servlet-name>FileUploadServlet</servlet-name>
		<url-pattern>/servlet/item/FileUploadServlet</url-pattern>
	</servlet-mapping>

	<servlet>
		<servlet-name>SearchItemServlet</servlet-name>
		<servlet-class>com.bjpowernode.drp.basedata.web.SearchItemServlet</servlet-class>
	</servlet>

	<servlet-mapping>
		<servlet-name>SearchItemServlet</servlet-name>
		<url-pattern>/servlet/item/SearchItemServlet</url-pattern>
	</servlet-mapping>

	<servlet>
		<servlet-name>ShowItemUploadServlet</servlet-name>
		<servlet-class>com.bjpowernode.drp.basedata.web.ShowItemUploadServlet</servlet-class>

	</servlet>

	<servlet-mapping>
		<servlet-name>ShowItemUploadServlet</servlet-name>
		<url-pattern>/servlet/item/ShowItemUploadServlet</url-pattern>
	</servlet-mapping>


	<error-page>
		<exception-type>com.bjpowernode.drp.util.ApplicationException</exception-type>
		<location>/error.jsp</location>
	</error-page>

	<error-page>
		<error-code>404</error-code>
		<location>/http_error.jsp</location>
	</error-page>


	<error-page>
		<error-code>500</error-code>
		<location>/500.jsp</location>
	</error-page>

</web-app>

    当然对于不同文件的处理还有很多可以优化的地方,这里只是提供了一种实现的方式,希望可以帮到大家!

评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值