码迷,mamicode.com
首页 > Web开发 > 详细

struts2中实现文件上传功能

时间:2014-10-30 22:37:01      阅读:214      评论:0      收藏:0      [点我收藏+]

标签:struts2   文件上传   


在web项目中,文件上传、头像上传这样的功能经常是要用到的,下面就以在struts2中实现文件上传功能为例子,简单地理一下文件上传功能的编码思路。


项目目录结构

bubuko.com,布布扣

项目源代码


web.xml

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

  <filter>
      <filter-name>struts 2</filter-name>
      <filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>
  </filter>
  <filter-mapping>
      <filter-name>struts 2</filter-name>
      <url-pattern>/*</url-pattern>
  </filter-mapping>
  
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
  
</web-app>


struts.xml

<span style="font-size:12px;"><?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
    "http://struts.apache.org/dtds/struts-2.3.dtd">
    
<struts>
    <package name="default" extends="struts-default">
        <action name="upload" class="com.upload.action.UploadAction" method="upload">
            <result name="success">/success.jsp</result>
            <result name="error">/upload.jsp</result>
        </action>
    </package>
</struts></span>


UploadAction.java

package com.upload.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.UUID;

import javax.servlet.ServletContext;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class UploadAction extends ActionSupport{

	private File upload;              //上传文件
	private String uploadFileName;    //上传的文件名
	
	public File getUpload(){
	    return upload;
	}
	
	public void setUpload(File upload){
		this.upload = upload;
	}
	
	public String getUploadFileName(){
		return uploadFileName;
	}
	
	public void setUploadFileName(String uploadFileName){
		this.uploadFileName = uploadFileName;
	}
	
	
	
	public String upload() throws Exception{
		
		//如果选择了上传功能,则执行上传操作;否则,不作任何操作
		if(getUpload() != null){	
			//根据上传的文件得到输入流
			InputStream is = new FileInputStream(getUpload());
			//更改上传文件名为:随机数+上传文件名		
			setUploadFileName(UUID.randomUUID().toString()+ getUploadFileName());
			//指定输出流地址,此处是输出到服务器项目的根目录下的images/userPhoto下
			OutputStream os = new FileOutputStream(getWebRootPath() + "images\\userPhoto\\" + getUploadFileName());
			
			byte buffer[] = new byte[1024];
			int count = 0;
			//把文件写到指定位置的文件中
			while((count = is.read(buffer)) > 0){
				os.write(buffer, 0, count);
			}
			//关闭输出流对象
			os.close();
			//关闭输入流对象
			is.close();
			//返回
			return SUCCESS;
		}
		else {
			return ERROR;
		}
	}
		
	/**
	 * 获得web项目根目录
	 */
	public String getWebRootPath() throws Exception {
		ActionContext actionContext = ActionContext.getContext();
		ServletContext servletContext = (ServletContext)actionContext.get(ServletActionContext.SERVLET_CONTEXT);
		String rootPath = servletContext.getRealPath("/");
		return rootPath;
	}
}<strong>
</strong>


upload.jsp

<span style="font-size:12px;"><%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="/struts-tags" prefix="s" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">    
    <title>文件上传</title>
  </head>
  
  <body>
      <s:form action="upload.action" method="post" enctype="multipart/form-data">
          <label for="photoPath">头像:</label>
          <input type="text" id="photoPath" disabled="disabled"/>
          <input type="button" onclick="myfile.click();" value="选择图片" id="select"/><br />
          <input type="file" id="myfile" name="upload"  onchange="photoPath.value=this.value" style="display:none" />
          <input type="submit" value="上传" />
      </s:form>
  </body>
</html></span><strong style="font-size:14px;">
</strong>


success.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>上传成功</title>
  </head>
  <body>
            恭喜您,文件上传成功!点<a href="upload.jsp">这里</a>回去
  </body>
</html>


上面的方法不仅可用于上传图片类型,也适用于其他文件类型的上传。

注意: Struts 2上传文件的默认大小限制是2MB,所以在测试的时候文件不能太大,最好找个小的文件。 如果要修改默认大小,只需要在Struts 2的struts.properties或struts.xml中修改struts.multipart.maxSize的值,如struts.multipart.maxSize=1024表示上传文件的总大小不能超过1KB 。

如在struts.xml中设置上传的文件大小不超过50MB,可以在struts.xml的<struts> </struts>标签里面添加:

<constant name="struts.multipart.maxSize" value="51200"/>




struts2中实现文件上传功能

标签:struts2   文件上传   

原文地址:http://blog.csdn.net/wangcunhuazi/article/details/40628423

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!