java实现图片上传
程序员文章站
2022-07-10 20:27:14
...
<p>一.在JSP环境中利用Commons-fileupload组件实现文件上传
1.页面upload.jsp清单如下:
Java代码 1
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%></p><p><!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>
注意:在上传表单中,既有普通文本域也有文件上传域 </p><p>2.FileUplaodServlet.java清单如下:
Java代码
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代码
<?xml version="1.0" encoding="UTF-8"?>
web-app version="2.4"
xmlns="<a href="http://java.sun.com/xml/ns/j2ee" target="_blank">http://java.sun.com/xml/ns/j2ee</a>"
xmlns:xsi="<a href="http://www.w3.org/2001/XMLSchema-instance" target="_blank">http://www.w3.org/2001/XMLSchema-instance</a>"
xsi:schemaLocation="<a href="http://java.sun.com/xml/ns/j2ee" target="_blank">http://java.sun.com/xml/ns/j2ee</a>
<a href="http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd" target="_blank">http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd</a>">
<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> </p><p>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> </p><p>
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 </p><p>4.struts.xml清单如下: </p><p>Java代码
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"<a href="http://struts.apache.org/dtds/struts-2.0.dtd" target="_blank">http://struts.apache.org/dtds/struts-2.0.dtd</a>">
<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代码
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4"
xmlns="<a href="http://java.sun.com/xml/ns/j2ee" target="_blank">http://java.sun.com/xml/ns/j2ee</a>"
xmlns:xsi="<a href="http://www.w3.org/2001/XMLSchema-instance" target="_blank">http://www.w3.org/2001/XMLSchema-instance</a>"
xsi:schemaLocation="<a href="http://java.sun.com/xml/ns/j2ee" target="_blank">http://java.sun.com/xml/ns/j2ee</a>
<a href="http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd" target="_blank">http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd</a>">
<filter >
<filter-name > struts-cleanup </filter-name >
<filter-class >
org.apache.struts2.dispatcher.ActionContextCleanUp
</filter-class >
</filter >
<filter-mapping >
<filter-name > struts-cleanup </filter-name >
<url-pattern > /* </url-pattern >
</filter-mapping >
<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>
<welcome-file-list>
<welcome-file>Index.jsp</welcome-file>
</welcome-file-list>
</web-app>
上一篇: Java-杨辉三角
下一篇: java实现上传图片(tcp)