大图片上传(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();
}
}
}
}
大图片上传(ImageIO,注意有的图片不能上传时因为他是tiff格式)的更多相关文章
- 从web编辑器 UEditor 中单独提取图片上传,包含多图片单图片上传以及在线涂鸦功能
UEditor是由百度web前端研发部开发所见即所得富文本web编辑器,具有轻量,可定制,注重用户体验等特点,开源基于MIT协议,允许自由使用和修改代码.(抄的...) UEditor是非常好用的富文 ...
- OAF_文件系列4_实现OAF上传显示数据库动态图片Image(案例)
20150805 Created By BaoXinjian
- .net mvc + layui做图片上传(二)—— 使用流上传和下载图片
摘要:上篇文章写到一种上传图片的方法,其中提到那种方法的局限性,就是上传的文件只能保存在本项目目录下,在其他目录中访问不到该文件.这与浏览器的安全性机制有关,浏览器不允许用户用任意的路径访问服务器上的 ...
- springboot上传文件并检查图片大小与格式
@PostMapping(value = "/uploadDriverImage") public JsonResVo uploadDriverImage(@RequestPara ...
- Jquery图片上传组件,支持多文件上传
Jquery图片上传组件,支持多文件上传http://www.jq22.com/jquery-info230jQuery File Upload 是一个Jquery图片上传组件,支持多文件上传.取消. ...
- iOS 使用AFN 进行单图和多图上传 摄像头/相册获取图片,压缩图片
图片上传时必要将图片进行压缩,不然会上传失败 首先是同系统相册选择图片和视频.iOS系统自带有UIImagePickerController,可以选择或拍摄图片视频,但是最大的问题是只支持单选,由于项 ...
- Facebook图片存储系统Haystack——存小文件,本质上是将多个小文件合并为一个大文件来降低io次数,meta data里存偏移量
转自:http://yanyiwu.com/work/2015/01/04/Haystack.html 一篇14页的论文Facebook-Haystack, 看完之后我的印象里就四句话: 因为[传统文 ...
- js插件---IUpload文件上传插件(包括图片)
js插件---IUpload文件上传插件(包括图片) 一.总结 一句话总结:上传插件找到真正上传位置的代码,这样就可以知道整个上传插件的逻辑了, 找资料还是github+官方 1.如何在js中找到真正 ...
- Thinkphp5图片上传正常,音频和视频上传失败的原因及解决
Thinkphp5图片上传正常,音频和视频上传失败的原因及解决 一.总结 一句话总结:php中默认限制了上传文件的大小为2M,查找错误的时候百度,且根据错误提示来查找错误. 我的实际问题是: 我的表单 ...
随机推荐
- Appium自动化测试框架
1.在utils包中创建一个AppiumUtil类,这个类是对appium api进行封装的. 代码如下: package utils; import java.net.MalformedURLExc ...
- P2764 最小路径覆盖问题(网络流24题之一)
题目描述 «问题描述: 给定有向图G=(V,E).设P 是G 的一个简单路(顶点不相交)的集合.如果V 中每个顶点恰好在P 的一条路上,则称P是G 的一个路径覆盖.P 中路径可以从V 的任何一个顶点开 ...
- [BZOJ1588][HNOI2002]营业额统计 无旋Treap
[HNOI2002]营业额统计 时间限制: 5 Sec 内存限制: 162 MB 题目描述 营业额统计 Tiger最近被公司升任为营业部经理,他上任后接受公司交给的第一项任务便是统计并分析公司成立以 ...
- Java发送http get/post请求,调用接口/方法
由于项目中要用,所以找了一些资料,整理下来. GitHub地址: https://github.com/iamyong 转自:http://blog.csdn.net/capmiachael/a ...
- BZOJ 4864: [BeiJing 2017 Wc]神秘物质 解题报告
4864: [BeiJing 2017 Wc]神秘物质 Description 21ZZ 年,冬. 小诚退休以后, 不知为何重新燃起了对物理学的兴趣. 他从研究所借了些实验仪器,整天研究各种微观粒子. ...
- Mac下安装MacProt,并GNU autotools的安装和使用 autoconf,automake
1 MacPort的下载:http://www.macports.org/install.php, 需要安装xCode支持macport 2 安装MacPorts 与其他Mac的软件的安装方式相同,挂 ...
- python基础----列表生成式、生成器表达式
结论: 1.把列表解析的[]换成()得到的就是生成器表达式 2.列表解析与生成器表达式都是一种便利的编程方式,只不过生成器表达式更节省内存 3.Python不但使用迭代器协议,让for循环变得更加通用 ...
- matlab图像
1.在网络上发现matlab能画出一些很有意思的图形(立体爱心) clc; const=0; x=-5:0.05:5;y=-5:0.05:5;z=-5:0.05:5; [x,y,z]=meshgrid ...
- spring mybatis 多数据源配置
1.创建好数据库的配置文件 mysql.url=jdbc:mysql://***/***?useUnicode=true&characterEncoding=UTF-8 mysql.usern ...
- Codeforces 19.E Fairy
E. Fairy time limit per test 1.5 seconds memory limit per test 256 megabytes input standard input ou ...