java实现图片上传
一.在JSP环境中利用Commons-fileupload组件实现文件上传
1.页面upload.jsp清单如下:
Java代码 1.<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
2.
3.<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
4.<html>
5. <head>
6. <title>The FileUpload Demo</title>
7. </head>
8.
9. <body>
10. <form action="UploadFile" method="post" enctype="multipart/form-data">
11. <p><input type="text" name="fileinfo" value="">文件介绍</p>
12. <p><input type="file" name="myfile" value="浏览文件"></p>
13. <p><input type="submit" value="上 传"></p>
14. </form>
15. </body>
16.</html>
<%@ 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代码 1.package org.chris.fileupload;
2.
3.import java.io.File;
4.import java.io.IOException;
5.import java.util.Iterator;
6.import java.util.List;
7.
8.import javax.servlet.ServletException;
9.import javax.servlet.http.*;
10.
11.import org.apache.commons.fileupload.FileItem;
12.import org.apache.commons.fileupload.FileItemFactory;
13.import org.apache.commons.fileupload.disk.DiskFileItemFactory;
14.import org.apache.commons.fileupload.servlet.ServletFileUpload;
15.
16.public class FileUplaodServlet extends HttpServlet {
17.
18. protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
19. doPost(request, response);
20. }
21.
22. protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
23.
24. request.setCharacterEncoding("UTF-8");
25.
26. //文件的上传部分
27. boolean isMultipart = ServletFileUpload.isMultipartContent(request);
28.
29. if(isMultipart)
30. {
31. try {
32. FileItemFactory factory = new DiskFileItemFactory();
33. ServletFileUpload fileload = new ServletFileUpload(factory);
34.
35.// 设置最大文件尺寸,这里是4MB
36. fileload.setSizeMax(4194304);
37. List<FileItem> files = fileload.parseRequest(request);
38. Iterator<FileItem> iterator = files.iterator();
39. while(iterator.hasNext())
40. {
41. FileItem item = iterator.next();
42. if(item.isFormField())
43. {
44. String name = item.getFieldName();
45. String value = item.getString();
46. System.out.println("表单域名为: " + name + "值为: " + value);
47. }else
48. {
49. //获得获得文件名,此文件名包括路径
50. String filename = item.getName();
51. if(filename != null)
52. {
53. File file = new File(filename);
54. //如果此文件存在
55. if(file.exists()){
56. File filetoserver = new File("d:\\upload\\",file.getName());
57. item.write(filetoserver);
58. System.out.println("文件 " + filetoserver.getName() + " 上传成功!!");
59. }
60. }
61. }
62. }
63. } catch (Exception e) {
64. System.out.println(e.getStackTrace());
65. }
66. }
67. }
68.}
package org.chris.fileupload;
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代码 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.
8. <servlet>
9. <servlet-name>UploadFileServlet</servlet-name>
10. <servlet-class>
11. org.chris.fileupload.FileUplaodServlet
12. </servlet-class>
13. </servlet>
14.
15. <servlet-mapping>
16. <servlet-name>UploadFileServlet</servlet-name>
17. <url-pattern>/UploadFile</url-pattern>
18. </servlet-mapping>
19.
20. <welcome-file-list>
21. <welcome-file>/Index.jsp</welcome-file>
22. </welcome-file-list>
23.
24.</web-app>
<?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代码 1.<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
2.<%@ taglib prefix="s" uri="/struts-tags" %>
3.<html>
4. <head>
5. <title>The FileUplaodDemo In Struts2</title>
6. </head>
7.
8. <body>
9. <s:form action="fileUpload.action" method="POST" enctype="multipart/form-data">
10. <s:file name="myFile" label="MyFile" ></s:file>
11. <s:textfield name="caption" label="Caption"></s:textfield>
12. <s:submit label="提交"></s:submit>
13. </s:form>
14. </body>
15.</html>
<%@ 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代码 1.<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
2.<%@ taglib prefix="s" uri="/struts-tags" %>
3.<html>
4. <head>
5. <title>ShowUpload</title>
6. </head>
7.
8. <body>
9. <div style ="padding: 3px; border: solid 1px #cccccc; text-align: center" >
10. <img src ='UploadImages/<s:property value ="imageFileName"/> '/>
11. <br />
12. <s:property value ="caption"/>
13. </div >
14. </body>
15.</html>
<%@ 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代码 1.package com.chris;
2.
3.import java.io.*;
4.import java.util.Date;
5.
6.import org.apache.struts2.ServletActionContext;
7.
8.
9.import com.opensymphony.xwork2.ActionSupport;
10.
11.public class FileUploadAction extends ActionSupport{
12.
13. private static final long serialVersionUID = 572146812454l ;
14. private static final int BUFFER_SIZE = 16 * 1024 ;
15.
16. //注意,文件上传时<s:file/>同时与myFile,myFileContentType,myFileFileName绑定
17. //所以同时要提供myFileContentType,myFileFileName的set方法
18.
19. private File myFile; //上传文件
20. private String contentType;//上传文件类型
21. private String fileName; //上传文件名
22. private String imageFileName;
23. private String caption;//文件说明,与页面属性绑定
24.
25. public void setMyFileContentType(String contentType) {
26. System.out.println("contentType : " + contentType);
27. this .contentType = contentType;
28. }
29.
30. public void setMyFileFileName(String fileName) {
31. System.out.println("FileName : " + fileName);
32. this .fileName = fileName;
33. }
34.
35. public void setMyFile(File myFile) {
36. this .myFile = myFile;
37. }
38.
39. public String getImageFileName() {
40. return imageFileName;
41. }
42.
43. public String getCaption() {
44. return caption;
45. }
46.
47. public void setCaption(String caption) {
48. this .caption = caption;
49. }
50.
51. private static void copy(File src, File dst) {
52. try {
53. InputStream in = null ;
54. OutputStream out = null ;
55. try {
56. in = new BufferedInputStream( new FileInputStream(src), BUFFER_SIZE);
57. out = new BufferedOutputStream( new FileOutputStream(dst), BUFFER_SIZE);
58. byte [] buffer = new byte [BUFFER_SIZE];
59. while (in.read(buffer) > 0 ) {
60. out.write(buffer);
61. }
62. } finally {
63. if ( null != in) {
64. in.close();
65. }
66. if ( null != out) {
67. out.close();
68. }
69. }
70. } catch (Exception e) {
71. e.printStackTrace();
72. }
73. }
74.
75. private static String getExtention(String fileName) {
76. int pos = fileName.lastIndexOf(".");
77. return fileName.substring(pos);
78. }
79.
80. @Override
81. public String execute() {
82. imageFileName = new Date().getTime() + getExtention(fileName);
83. File imageFile = new File(ServletActionContext.getServletContext().getRealPath("/UploadImages" ) + "/" + imageFileName);
84. copy(myFile, imageFile);
85. return SUCCESS;
86. }
87.}
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代码 1.<?xml version="1.0" encoding="UTF-8" ?>
2.<!DOCTYPE struts PUBLIC
3. "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
4. "http://struts.apache.org/dtds/struts-2.0.dtd">
5.<struts>
6. <package name="example" namespace="/" extends="struts-default">
7. <action name="fileUpload" class="com.chris.FileUploadAction">
8. <interceptor-ref name="fileUploadStack"/>
9. <result>/ShowUpload.jsp</result>
10. </action>
11. </package>
12.</struts>
<?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>
java上传图片
最新推荐文章于 2024-06-03 23:10:45 发布