大图片上传(ImageIO,注意有的图片不能上传时因为他是tiff格式)
一下是必要的:
1.enctype="multipart/form-data"
2.
//不要使用myeclipse自动生成的get、set方法(struts2中的用法)
public void setMyFileContentType(String contentType) {
System.out.println("contentType : " +
contentType);
this .contentType =
contentType;
}
public void setMyFileFileName(String fileName) {
System.out.println("FileName : " +
fileName);
this .fileName = fileName;
}
还有如果form不是用的struts2的标签表单<s:form>则web.xml中的配置不一定要使用/*,普通form *.action就行了!
注:如果是用struts2一般都是吧File封装成一个类来使用,这样会很方便文章后面的ImageUpload类(我进行了缩放处理,如果不需要放开注释代码就行了)。相应的<s:file name="ImageUpload.myFile"
label="MyFile" ></s:file>
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
一.在JSP环境中利用Commons-fileupload组件实现文件上传
1.页面upload.jsp清单如下:
Java代码 1.
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01
Transitional//EN">
<html>
<head>
<title>The FileUpload Demo</title>
</head>
<body>
<form action="UploadFile"
method="post" enctype="multipart/form-data">
<p><input type="text"
name="fileinfo" value="">文件介绍</p>
<p><input type="file"
name="myfile" value="浏览文件"></p>
<p><input type="submit"
value="上 传"></p>
</form>
</body>
</html>
注意:在上传表单中,既有普通文本域也有文件上传域
2.FileUplaodServlet.java清单如下:
Java代码
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.*;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
public class FileUplaodServlet extends HttpServlet {
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
//文件的上传部分
boolean isMultipart =
ServletFileUpload.isMultipartContent(request);
if(isMultipart)
{
try {
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload fileload = new
ServletFileUpload(factory);
// 设置最大文件尺寸,这里是4MB
fileload.setSizeMax(4194304);
List<FileItem> files =
fileload.parseRequest(request);
Iterator<FileItem> iterator =
files.iterator();
while(iterator.hasNext())
{
FileItem item = iterator.next();
if(item.isFormField())
{
String name = item.getFieldName();
String value = item.getString();
System.out.println("表单域名为: " + name + "值为: " + value);
}else
{
//获得获得文件名,此文件名包括路径
String filename = item.getName();
if(filename != null)
{
File file = new File(filename);
//如果此文件存在
if(file.exists()){
File filetoserver = new
File("d:\\upload\\",file.getName());
item.write(filetoserver);
System.out.println("文件 " + filetoserver.getName() + " 上传成功!!");
}
}
}
}
} catch (Exception e) {
System.out.println(e.getStackTrace());
}
}
}
}
3.web.xml清单如下:
Java代码
<?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">
<servlet>
<servlet-name>UploadFileServlet</servlet-name>
<servlet-class>
org.chris.fileupload.FileUplaodServlet
</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>UploadFileServlet</servlet-name>
<url-pattern>/UploadFile</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>/Index.jsp</welcome-file>
</welcome-file-list>
</web-app>
三.在struts2中实现(以图片上传为例)
1.FileUpload.jsp代码清单如下:
Java代码
<%@ page language="java"
import="java.util.*" pageEncoding="utf-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
<title>The FileUplaodDemo In Struts2</title>
</head>
<body>
<s:form action="fileUpload.action"
method="POST" enctype="multipart/form-data">
<s:file name="myFile"
label="MyFile" ></s:file>
<s:textfield name="caption"
label="Caption"></s:textfield>
<s:submit label="提交"></s:submit>
</s:form>
</body>
</html>
2.ShowUpload.jsp的功能清单如下:
Java代码
<%@ page language="java"
import="java.util.*" pageEncoding="utf-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
<title>ShowUpload</title>
</head>
<body>
<div style ="padding: 3px; border: solid 1px
#cccccc; text-align: center" >
<img src
='UploadImages/<s:property value ="imageFileName"/> '/>
<br />
<s:property value
="caption"/>
</div >
</body>
</html>
3.FileUploadAction.java的代码清单如下 :
Java代码
package com.chris;
import java.io.*;
import java.util.Date;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;
public class FileUploadAction extends ActionSupport{
private static final long serialVersionUID =
572146812454l ;
private static final int BUFFER_SIZE = 16 * 1024 ;
//注意,文件上传时<s:file/>同时与myFile,myFileContentType,myFileFileName绑定
//所以同时要提供myFileContentType,myFileFileName的set方法
private File myFile; //上传文件
private String contentType;//上传文件类型
private String fileName; //上传文件名
private String imageFileName;
private String caption;//文件说明,与页面属性绑定
public void setMyFileContentType(String
contentType) {
System.out.println("contentType : " +
contentType);
this .contentType =
contentType;
}
public void setMyFileFileName(String fileName) {
System.out.println("FileName : " +
fileName);
this .fileName = fileName;
}
public void setMyFile(File myFile) {
this .myFile = myFile;
}
public String getImageFileName() {
return imageFileName;
}
public String getCaption() {
return caption;
}
public void setCaption(String caption) {
this .caption = caption;
}
private static void copy(File src, File dst) {
try {
InputStream
in = null ;
OutputStream
out = null ;
try
{
in = new BufferedInputStream( new FileInputStream(src), BUFFER_SIZE);
out = new BufferedOutputStream( new FileOutputStream(dst), BUFFER_SIZE);
byte [] buffer = new byte [BUFFER_SIZE];
while (in.read(buffer) > 0 ) {
out.write(buffer);
}
}
finally {
if ( null != in) {
in.close();
}
if ( null != out) {
out.close();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
private static String getExtention(String
fileName) {
int pos =
fileName.lastIndexOf(".");
return
fileName.substring(pos);
}
@Override
public String execute()
{
imageFileName = new Date().getTime()
+ getExtention(fileName);
File imageFile = new
File(ServletActionContext.getServletContext().getRealPath("/UploadImages"
) + "/" + imageFileName);
copy(myFile, imageFile);
return SUCCESS;
}
}
注:此时仅为方便实现Action所以继承ActionSupport,并Overrider execute()方法
在struts2中任何一个POJO都可以作为Action
4.struts.xml清单如下:
Java代码
<?xml version="1.0" encoding="UTF-8"
?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts
Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<package name="example" namespace="/"
extends="struts-default">
<action name="fileUpload"
class="com.chris.FileUploadAction">
<interceptor-ref name="fileUploadStack"/>
<result>/ShowUpload.jsp</result>
</action>
</package>
</struts>
5.web.xml清单如下:
Java代码
1.<?xml version="1.0"
encoding="UTF-8"?>
2.<web-app version="2.4"
3. xmlns="http://java.sun.com/xml/ns/j2ee"
4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
5. xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
6. http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
7. <filter >
8. <filter-name >
struts-cleanup </filter-name >
9. <filter-class
>
10.
org.apache.struts2.dispatcher.ActionContextCleanUp
11. </filter-class
>
12. </filter >
13. <filter-mapping >
14. <filter-name >
struts-cleanup </filter-name >
15. <url-pattern > /*
</url-pattern >
16. </filter-mapping >
17.
18. <filter>
19.
<filter-name>struts2</filter-name>
20.
<filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>
21. </filter>
22. <filter-mapping>
23.
<filter-name>struts2</filter-name>
24.
<url-pattern>/*</url-pattern>
25. </filter-mapping>
26. <welcome-file-list>
27.
<welcome-file>Index.jsp</welcome-file>
28. </welcome-file-list>
29.
30.</web-app>
public class ImageUpload {
private static final long serialVersionUID = 572146812454l;
private static final int BUFFER_SIZE = 30000 * 1024;
private File myFile; // 上传文件
private String contentType;// 上传文件类型
private String fileName; // 上传文件名
private String imageFileName;
private String imageUrl = "/UploadImages" + "/" + fileName;
public String getImageUrl() {
return imageUrl;
}
public void setImageUrl(String imageUrl) {
this.imageUrl = imageUrl;
}
public void setMyFileContentType(String contentType) {
System.out.println("contentType : " + contentType);
this.contentType = contentType;
}
public void setMyFileFileName(String fileName) {
System.out.println("FileName : " + fileName);
this.fileName = fileName;
}
public void setMyFile(File myFile) {
this.myFile = myFile;
}
public String getImageFileName() {
return imageFileName;
}
public void setImageFileName(String imageFileName) {
this.imageFileName = imageFileName;
}
private static boolean copy(File src, File dst) {
boolean flag=false;
try {
InputStream in = null;
OutputStream out = null;
BufferedImage tag = null;
try {
if (src != null) {
BufferedImage src1 = javax.imageio.ImageIO.read(src); // 构造Image对象
// Image src1 = javax.imageio.ImageIO.read(src);
if(src1!=null){
int wideth = src1.getWidth(null); // 得到源图宽
System.out.println("wideth"+wideth);
int height = src1.getHeight(null); // 得到源图长
System.out.println("height"+height);
int newWidth;
int newHeight;
int outputWidth=1280;
int outputHeight=800;
if(wideth>1280){
System.out.println("qqqq");
// 判断是否是等比缩放
// 为等比缩放计算输出的图片宽度及高度
double rate1 = ((double) wideth) / (double) outputWidth + 0.1;
double rate2 = ((double) height) / (double) outputHeight + 0.1;
// 根据缩放比率大的进行缩放控制
double rate = rate1 > rate2 ? rate1 : rate2;
newWidth = (int) (((double) wideth) / rate);
newHeight = (int) (((double) height) / rate);
tag = new BufferedImage((int) newWidth, (int) newHeight, BufferedImage.TYPE_INT_RGB);
tag.getGraphics().drawImage(src1.getScaledInstance(newWidth, newHeight, Image.SCALE_SMOOTH), 0, 0, null); // 绘制缩小后的图
}else {
tag = new BufferedImage(wideth,
height, BufferedImage.TYPE_INT_RGB);
tag.getGraphics().drawImage(src1, 0, 0, wideth,
height, null); // 绘制缩小后的图
}
/*in = new BufferedInputStream(new FileInputStream(src),BUFFER_SIZE);
out = new BufferedOutputStream(new FileOutputStream(dst),
BUFFER_SIZE);
byte[] buffer = new byte[BUFFER_SIZE];
while (in.read(buffer) > 0) {
out.write(buffer);
JPEGImageEncoder encoder = JPEGCodec
.createJPEGEncoder(out);
encoder.encode(tag); // 近JPEG编码
out.close();
}*/
out = new FileOutputStream(dst);
// JPEGImageEncoder可适用于其他图片类型的转换
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
encoder.encode(tag);
out.close();
flag=true;
}
}
} finally {
if (null != in) {
in.close();
}
if (null != out) {
out.close();
}
}
} catch (Exception e) {
e.printStackTrace();
}
return flag;
}
public boolean saveImageUpload() {
System.out.println("saveImageUpload" + fileName);
boolean flag=false;
if (fileName != null) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
String date = sdf.format(new Date());
fileName=date+fileName;
File imageFile = new File(ServletActionContext.getServletContext().getRealPath("/UploadImages")+ "/" + fileName);
System.out.println(ServletActionContext.getServletContext()
.getRealPath("/UploadImages")
+ "/" + fileName);
imageUrl = "/UploadImages" + "/" + fileName;
flag=copy(myFile, imageFile);
}
return flag;
}
}
JDK宝典里有这样的一段代码,你调用copyFile方法就可以了:
/**
* 复制单个文件, 如果目标文件存在,则不覆盖。
* @param srcFileName 待复制的文件名
* @param destFileName 目标文件名
* @return 如果复制成功,则返回true,否则返回false
*/
public static boolean copyFile(String srcFileName, String destFileName){
return CopyFileUtil.copyFile(srcFileName, destFileName, false);
}
/**
* 复制单个文件
* @param srcFileName 待复制的文件名
* @param destFileName 目标文件名
* @param overlay 如果目标文件存在,是否覆盖
* @return 如果复制成功,则返回true,否则返回false
*/
public static boolean copyFile(String srcFileName,
String destFileName, boolean overlay) {
//判断原文件是否存在
File srcFile = new File(srcFileName);
if (!srcFile.exists()){
System.out.println("复制文件失败:原文件" + srcFileName + "不存在!");
return false;
} else if (!srcFile.isFile()){
System.out.println("复制文件失败:" + srcFileName + "不是一个文件!");
return false;
}
//判断目标文件是否存在
File destFile = new File(destFileName);
if (destFile.exists()){
//如果目标文件存在,而且复制时允许覆盖。
if (overlay){
//删除已存在的目标文件,无论目标文件是目录还是单个文件
System.out.println("目标文件已存在,准备删除它!");
if(!DeleteFileUtil.delete(destFileName)){
System.out.println("复制文件失败:删除目标文件" + destFileName + "失败!");
return false;
}
} else {
System.out.println("复制文件失败:目标文件" + destFileName + "已存在!");
return false;
}
} else {
if (!destFile.getParentFile().exists()){
//如果目标文件所在的目录不存在,则创建目录
System.out.println("目标文件所在的目录不存在,准备创建它!");
if(!destFile.getParentFile().mkdirs()){
System.out.println("复制文件失败:创建目标文件所在的目录失败!" );
return false;
}
}
}
//准备复制文件
int byteread = 0;//读取的位数
InputStream in = null;
OutputStream out = null;
try {
//打开原文件
in = new FileInputStream(srcFile);
//打开连接到目标文件的输出流
out = new FileOutputStream(destFile);
byte[] buffer = new byte[1024];
//一次读取1024个字节,当byteread为-1时表示文件已经读完
while ((byteread = in.read(buffer)) != -1) {
//将读取的字节写入输出流
out.write(buffer, 0, byteread);
}
System.out.println("复制单个文件" + srcFileName + "至" + destFileName + "成功!");
return true;
} catch (Exception e) {
System.out.println("复制文件失败:" + e.getMessage());
return false;
} finally {
//关闭输入输出流,注意先关闭输出流,再关闭输入流
if (out != null){
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (in != null){
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}