日期:2014-05-16  浏览次数:20381 次

struts2上传(图片带js预览)
jsp页面:
<%@ page language="java" contentType="text/html; charset=GBK"
    pageEncoding="GBK"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GBK">
<title>Insert title here</title>
</head>
<script type="text/javascript">
  // 显示图片的js
function viewimg(){
var imgup=document.getElementById("uploadimg");
var imgpath=getPath(imgup);
//判断是否是图片格式
var imgname=imgup.value.substring(imgup.value.lastIndexOf("."),imgup.value.length)
imgname=imgname.toLowerCase()
if ((imgname!='.jpg')&&(imgname!='.gif')&&(imgname!='.jpeg')&&(imgname!='.png')&&(imgname!='.bmp')){
alert("请选择图片文件,谢谢!");
imgup.focus();
//清空file里面的值
imgup.select();  
document.selection.clear();

}
else{
//显示图片
document.getElementById("sig_preview").innerHTML="<img src='"+imgpath+"' border=0 width=100 height=60>"
}
}
//该函数解决iE下路径问题。兼容ie6,7,firefox add by exceljava 2010-1-6
function getPath(obj){
   if(obj){
   if (window.navigator.userAgent.indexOf("MSIE")>=1){
     obj.select();
     return document.selection.createRange().text;
   }else if(window.navigator.userAgent.indexOf("Firefox")>=1){
     if(obj.files){
         return obj.files.item(0).getAsDataURL();  
     }
     return obj.value;
   }   
   return obj.value;   
   }
}



</script>
<body>
<s:form action ="fileUpload" namespace="/fileUploadDemo" method ="POST" enctype ="multipart/form-data">
<s:file id="uploadimg"  size="40" name="upload" onchange="viewimg()"></s:file>     
    <s:submit />
</s:form>

<!-- 显示的div -->
<div id="sig_preview"></div>
</body>
</html>

action代码:
package UploadImages;

import java.io.File;

import javax.servlet.ServletContext;

import org.apache.commons.io.FileUtils;
import org.apache.struts2.util.ServletContextAware;

import com.opensymphony.xwork2.ActionSupport;

public class FileUploadAction extends ActionSupport implements
        ServletContextAware {

    private File upload;// 实际上传文件

    private String uploadContentType; // 文件的内容类型

    private String uploadFileName; // 上传文件名

    private String fileCaption;// 上传文件时的备注
   
    private ServletContext context;

    public String execute() throws Exception {

        try {
           
            String targetDirectory = context.getRealPath("/UploadImages");
            String targetFileName = uploadFileName;
            File target = new File(targetDirectory, targetFileName);