上传图片和音频到Server,再转存到DB

jsp页面

<%@ page language="java" pageEncoding="UTF-8" contentType="text/html;charset=UTF-8"%>
<%@ include file="/common/taglibs.jsp"%>
<link rel="stylesheet" href="<c:url value='/plugin/ztree-v3.5.14/css/zTreeStyle/zTreeStyle.css'/>" type="text/css">
<script type="text/javascript" src="<c:url value='/plugin/ztree-v3.5.14/js/jquery.ztree.core-3.5.js'/>"></script>
<script type="text/javascript" src="<c:url value='/plugin/ztree-v3.5.14/js/jquery.ztree.excheck-3.5.js'/>"></script>
<script type="text/javascript" src="<c:url value='/plugin/ztree-v3.5.14/js/jquery.ztree.exedit-3.5.js'/>"></script>
<script language="javascript" type="text/javascript" src="<c:url value='/plugin/artDialog4.1.7/jquery.artDialog.js?skin=simple'/>"></script>
<script language="javascript" type="text/javascript" src="<c:url value='/plugin/artDialog4.1.7/plugins/iframeTools.js'/>"></script>
<script language= javascript  type= text/javascript  src="<c:url value='/default/scripts/jquery.form.js'/>" ></script>
<style>
<!--
input[type=text],select,textarea {
	width:300px;
}
 .mouse_pointer{
 	cursor:pointer;
 }
 label.align_top {
 	vertical-align: top;
 }
 label.align_mid {
 	vertical-align: middle;
 }
 textarea {
 	margin:0;
 	padding:0;
 	height:50px;
 }
 #editCourse_table {
	border: transparent;
	border-collapse: collapse;
	font-family: Arial,Helvetica,sans-serif;
	margin-top: 10px;
 }
 .editCourse_table td{
	/*background-color: #EFEFEF;*/
	border: transparent;
	padding: 5px 15px 5px 5px;
	vertical-align: middle;
	width:65%;
 }
 .editCourse_table td:first-child{
 	text-align: right;
 	width:20%;
 }
 .editCourse_table td:last-child {
 	text-align:left;
 	width:12px;
 }
 
 .notNullStar {
 	vertical-align: sub;
 }
 .hidden {
 	display: none;
 }
-->
</style>


<script>

	var saved;
	
	//值改变函数
	function valueChanged(elem){
		saved = false;
	}

	function reDisplay( wordDicObj ){
		$("input[name='wordDictionaryVo.word']").val(wordDicObj.word);
		$("input[name='wordDictionaryVo.abbreviative']").each(function(){
				$(this).removeAttr("checked");
		});
		if( wordDicObj.abbreviative == true ){
			$("input[name='wordDictionaryVo.abbreviative'][value='true']").attr("checked", true);
		}
		else{
			$("input[name='wordDictionaryVo.abbreviative'][value='false']").attr("checked", true);
		}
		
		//释义
		if( wordDicObj.wordExplain != null && wordDicObj.wordExplain != "" ){
			$("textarea[name='wordDictionaryVo.wordExplain']").val(wordDicObj.wordExplain);
		}
		
		if( wordDicObj.simpleExplain != null && wordDicObj.simpleExplain != "" ){
			$("textarea[name='wordDictionaryVo.simpleExplain']").val(wordDicObj.simpleExplain);
		}
		
		$("#wordImage").attr("src", "<c:url value='/worddictionary/getImageById.action?id='/>" + wordDicObj.id);
		
		if( wordDicObj.ukPhoneticSymbol != null && wordDicObj.ukPhoneticSymbol != "" ){
			$("input[name='wordDictionaryVo.ukPhoneticSymbol']").val(wordDicObj.ukPhoneticSymbol);
		}
		
		if( wordDicObj.ukPhoneSplit != null && wordDicObj.ukPhoneSplit != "" ){
			$("input[name='wordDictionaryVo.ukPhoneSplit']").val(wordDicObj.ukPhoneSplit);
		}
		
		if( wordDicObj.ukWordSplit != null && wordDicObj.ukWordSplit != "" ){
			$("input[name='wordDictionaryVo.ukWordSplit']").val(wordDicObj.ukWordSplit);
		}
		
		if( wordDicObj.ukAudioExist != null && wordDicObj.ukAudioExist == true ){
			$("#ukspeaker").attr("audioUrl","<c:url value='/worddictionary/getAudioByIdAndCountry.action?id='/>" + wordDicObj.id + "&countryType=uk");
			$("#ukspeaker").show();
		}
		else{
			$("#ukspeaker").attr("audioUrl","");
			$("#ukspeaker").hide();
		}
		
		if( wordDicObj.usPhoneticSymbol != null && wordDicObj.usPhoneticSymbol != "" ){
			$("input[name='wordDictionaryVo.usPhoneticSymbol']").val(wordDicObj.usPhoneticSymbol);
		}
		
		if( wordDicObj.usPhoneSplit != null && wordDicObj.usPhoneSplit != "" ){
			$("input[name='wordDictionaryVo.usPhoneSplit']").val(wordDicObj.usPhoneSplit);
		}
		
		if( wordDicObj.usWordSplit != null && wordDicObj.usWordSplit != "" ){
			$("input[name='wordDictionaryVo.usWordSplit']").val(wordDicObj.usWordSplit);
		}
		
		if( wordDicObj.usAudioExist != null && wordDicObj.usAudioExist == true ){
			$("#usspeaker").attr("audioUrl","<c:url value='/worddictionary/getAudioByIdAndCountry.action?id='/>" + wordDicObj.id + "&countryType=us");
			$("#usspeaker").show();
		}
		else{
			$("#usspeaker").attr("audioUrl","");
			$("#usspeaker").hide();
		}
	}
	
	function clearDisplay(){
		$("input[name='wordDictionaryVo.abbreviative']").each(function(){
				$(this).removeAttr("checked");
		});
		$("input[name='wordDictionaryVo.abbreviative'][value='false']").attr("checked", true);
		$("textarea[name='wordDictionaryVo.wordExplain']").val("");
		$("textarea[name='wordDictionaryVo.simpleExplain']").val("");
		$("#wordImage").attr("src", "<c:url value='/worddictionary/getImageById.action?id='/>");
		$("input[name='wordDictionaryVo.ukPhoneticSymbol']").val("");
		$("input[name='wordDictionaryVo.ukPhoneSplit']").val("");
		$("input[name='wordDictionaryVo.ukWordSplit']").val("");
		$("#ukspeaker").attr("audioUrl","");
		$("#ukspeaker").hide();
		$("input[name='wordDictionaryVo.usPhoneticSymbol']").val("");
		$("input[name='wordDictionaryVo.usPhoneSplit']").val("");
		$("input[name='wordDictionaryVo.usWordSplit']").val("");
		$("#usspeaker").attr("audioUrl","");
		$("#usspeaker").hide();
	}
	
	$(function(){
		
		//radio输入改变事件
		$("input[type=radio]").change(function(){
			valueChanged(this);
		});
		
		$("input[type=text],textarea").bind("input propertychange",function(){
			valueChanged(this);
		});
		
		$("#word").keydown(function( evt ){
			if( evt.keyCode == 13 ){
				$("#queryButton").trigger("click");
			}
		});
		
		//单词查询Button
		$("#queryButton").click(function(){
			if($("#wordForm").validate().form()){
				var word = $.trim($("#word").val());
	  			$.ajax({
	  				url: "<s:url value='/worddictionary/getWordDictionaryByWord.action'/>",
	  				type: "post",
	  				async:true,
	  				data:{word:word},
	  				dataType: "json",
	  				contentType:"application/x-www-form-urlencoded; charset=UTF-8" ,   //
	  				success: function( rtnValue ){
	  					if(rtnValue== null ){
	  						clearDisplay();
	  						art.tips("单词或词组不存在,赶紧添加吧!",2);
	  					}
	  					else{
	  						clearDisplay();
	  						reDisplay( rtnValue );
	  					}
	  				},
	  				error: function(reqObj, strError, strObj){
						
	  				}
	  			});
			}
		});
		
		$.validator.addMethod("validChar", function(value, element, params){
			value = $.trim(value);
			if (/^[\w|\s|\-|']*$/.test(value)) {
				return true;
			}
			
			return false;
		},"单词或词组包含非法字符" );
		
		$("#wordForm").validate({
			
			//显示错误信息用的标签类型
			errorElement: "em",
			//验证规则
			rules: {
				"wordDictionaryVo.word":{
					required: true,
					maxlength:256,
					validChar: true
				}
			},
			messages: {
			  	"wordDictionaryVo.word":{
			  		required:"请输入单词或词组",
			  		maxlength:"单词或词组总长度太长",
			  		checkBlank:"单词或词组不能为空串",
			  		validChar:"单词或词组包含非法字符"
			  	}
			}
		});
		
		//保存
		$("#saveButton").click(function(){
			if(!$("#wordForm").validate().form()){
				var errorMessage = "";
				$("em.error").each(function(){
					errorMessage += $(this).text() + "<br/>";
				});
				art.tips(errorMessage,2.5);
				return;
			}
			if(saved){
				art.tips("已成功保存或无更改,无需再次保存",2.5);
				return;
			}
			
			$("#wordForm").ajaxSubmit({
	       		type:"post",
	       		dataType:"json",
	       		success: function(response) {
	       			if(response.message.saveSuccess){
	       				art.tips("保存成功!",1.5);
		               	saved = true;
	       			}else{
	       				art.tips("保存失败,"+response.message.errorMsg,2.5);
	       			}
	               	
		        },
				error:function(response){
					art.tips("保存失败,网络错误",2.5);
				}
			});
		});
		
		//上传图片
		$("#uploadImage").click(function(evt){
			evt.preventDefault();
			var val = $(this).attr("name");
			art.dialog.data('name', val);
			art.dialog.open('<c:url value="/worddictionary/uploadImageDialog.action"/>',{
				id: 'iframedialogUpload',
				title: '',
	            lock: true,
	            width:400,
	            drag:false,
	            height:150,
				init: function () {
			    	var iframe = this.iframe.contentWindow; //获取子页面对象
			    	var top = art.dialog.top;// 获取父页面对象
					
			    }
			},false);
		});
		
		//上传音频
		$("#uploadUKAudio,#uploadUSAudio").click(function(evt){
			evt.preventDefault();
			var val = $(this).attr("name");
			art.dialog.data('name', val);
			art.dialog.open('<c:url value="/worddictionary/uploadAudioDialog.action"/>',{
				id: 'iframedialogUpload',
				title: '',
	            lock: true,
	            width:400,
	            drag:false,
	            height:150,
				init: function () {
			    	var iframe = this.iframe.contentWindow; //获取子页面对象
			    	var top = art.dialog.top;// 获取父页面对象
					
			    }
			},false);
		});
		
		$(".speaker").click(function(){
			var audioUrl = $(this).attr("audioUrl");
			thisMovie("wordDictionary_mp3Player").playAudio(audioUrl);
		});
	
});

function changeImage(name,imageName){
	$("#"+name).attr("src","<s:url value='/temp/images/'/>"+imageName);
	$("#"+name +"_hidden").val(imageName);
	saved = false;
}

function changeAudio(name, audioName){
	var audioUrl = "<c:url value='/worddictionary/getAudioByFileName.action?audioServerFileName='/>" + audioName;
	$("#"+name).attr("audioUrl", audioUrl);
	$("#"+name).show();
	$("#"+name +"_hidden").val(audioName);
	saved = false;
}


function thisMovie(movieName) {
    if (navigator.appName.indexOf("Microsoft") != -1) {
        return window[movieName];
    }else {
        return document[movieName];
    }
}

</script>

<!-- 隐藏的ActionScript播放器类  -->
<!--  
<object style="width: 1px; height: 1px;position: absolute; top:0px; left:0px;" type="application/x-shockwave-flash" data="<c:url value='/flash/NetStreamAudioPlayerAS.swf?onLoadCompleted=onPlayerCompleted'/>" name="wordDictionaryAudioPlayer" id="wordDictionaryAudioPlayer" >
	<param name="allowScriptAccess" value="sameDomain" />
	<param name="movie" value="<c:url value='/flash/NetStreamAudioPlayerAS.swf?onLoadCompleted=onPlayerCompleted'/>" />
	<param name="quality" value="high" />
	<param name="scale" value="noScale" />
	<param name="wmode" value="transparent" />
</object>
-->

<object style="width: 0px; height: 0px;" type="application/x-shockwave-flash" data="/flash/Mp3PlayerAS.swf" name="wordDictionary_mp3Player" id="wordDictionary_mp3Player" >
	<param name="allowScriptAccess" value="sameDomain" />
	<param name="movie" value="/flash/Mp3PlayerAS.swf" />
	<param name="visible" value="false" />
</object>


<span class="font-18">单词编辑</span>
<form action="<c:url value='/worddictionary/saveWordDictionary.action'/>" method="post" id="wordForm" name="wordForm">
	<div style="width:860px;">
	<table id="editCourse_table" class="editCourse_table">
	<!-- 编辑区,公有属性 -->
	<tbody>
		<tr>
			<td>
				<label><span class="font-red notNullStar">*</span>单词:</label>
			</td>
			<td>
				<s:textfield id="word" name="wordDictionaryVo.word"/>
				<input type="button" class="button" name="queryButton"  value="查询" id="queryButton"/>
			</td>
		</tr>
		<tr>
			<td>
				<label>是否是缩写:</label>
			</td>
			<td>
				<input type="radio" name="wordDictionaryVo.abbreviative" value="false" checked/>否
				<input type="radio" name="wordDictionaryVo.abbreviative" value="true"/>是
			</td>
		</tr>
		<tr>
			<td>
				<label>释义:</label>
			</td>
			<td>
				<s:textarea id="wordExplain" cols="50" name="wordDictionaryVo.wordExplain" />
			</td>
		</tr>
		<tr>
			<td>
				<label>简单释义:</label>
			</td>
			<td>
				<s:textarea id="simpleExplain" cols="50" name="wordDictionaryVo.simpleExplain" />
			</td>
		</tr>
		<tr>
			<td>
				<label for="iconImage" class="align_top">图片:</label>
			</td>
			<td>
				<img id="wordImage" style="width:140px;height:210px;border: 1px black solid;" src="<c:url value='/worddictionary/getImageById.action?id='/>${wordDictionaryVo.id}"/>
				<s:hidden id="wordImage_hidden" name="wordDictionaryVo.imageServerFileName" onpropertychange="valueChanged(this)"/>
				<a href="#" id="uploadImage" name="wordImage">上传图片</a>
			</td>
		</tr>
		<tr>
			<td>
				<label>英式音标:</label>
			</td>
			<td>
				<s:textfield id="ukPhoneticSymbol" name="wordDictionaryVo.ukPhoneticSymbol"/>
			</td>
		</tr>
		<tr>
			<td>
				<label>英式发音音标分解:</label>
			</td>
			<td>
				<s:textfield id="ukPhoneSplit" name="wordDictionaryVo.ukPhoneSplit"/>
			</td>
		</tr>
		<tr>
			<td>
				<label>英式发音单词分解:</label>
			</td>
			<td>
				<s:textfield id="ukWordSplit" name="wordDictionaryVo.ukWordSplit"/>
			</td>
		</tr>
		<tr>
			<td>
				<label>英式发音:</label>
			</td>
			<td>
				<input id="ukspeaker" class="icon-button speaker" audioUrl="" audioType="mp3" type="button" style="display:none;">
				<s:hidden id="ukspeaker_hidden" name="wordDictionaryVo.ukAudioServerFileName"/>
				<a href="#" id="uploadUKAudio" name="ukspeaker">上传音频</a>
			</td>
		</tr>
		<tr>
			<td>
				<label>美式音标:</label>
			</td>
			<td>
				<s:textfield id="usPhoneticSymbol" name="wordDictionaryVo.usPhoneticSymbol"/>
			</td>
		</tr>
		<tr>
			<td>
				<label>美式发音音标分解:</label>
			</td>
			<td>
				<s:textfield id="usPhoneSplit" name="wordDictionaryVo.usPhoneSplit"/>
			</td>
		</tr>
		<tr>
			<td>
				<label>美式发音单词分解:</label>
			</td>
			<td>
				<s:textfield id="usWordSplit" name="wordDictionaryVo.usWordSplit"/>
			</td>
		</tr>
		<tr>
			<td>
				<label>美式发音:</label>
			</td>
			<td>
				<input id="usspeaker" class="icon-button speaker" audioUrl="" audioType="mp3" type="button" style="display:none;">
				<s:hidden id="usspeaker_hidden" name="wordDictionaryVo.usAudioServerFileName"/>
				<a href="#" id="uploadUSAudio" name="usspeaker">上传音频</a>
			</td>
		</tr>
		<tr>
			<td>
			</td>
			<td>
				<input type="button" class="button" name="saveButton"  value="保存" id="saveButton"/>
			</td>
		</tr>
	</tbody>
	</table>
	</div>
	
</form>


Action XML配置

<?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="worddictionary" namespace="/worddictionary" extends="web-default">
		<!-- 
			到编辑单词主页
		 -->
		<action name="editWordDictionary" class="newWordDictionaryAction" method="editWordDictionary">
			<result name="success" type="tiles">editWordDictionary</result>
		</action>
		
		<!--
			根据id获取图片
		-->
		<action name="getImageById" class="newWordDictionaryAction" method="getImageById">
			<result name="success" type="stream">  
               <param name="contentType">image/jpeg</param>  
               <param name="inputName">imageStream</param>  
               <param name="bufferSize">2048</param>  
            </result>
		</action>
		
		<!-- 
			根据单词或词组查询字典
		 -->
		<action name="getWordDictionaryByWord" class="newWordDictionaryAction" method="getWordDictionaryByWord">
			<result name="ajax" type="json">
				<param name="include">wordDictionaryVo</param>
			</result>
		</action>
		
		<!-- 
			保存单词或词组到字典
		 -->
		<action name="saveWordDictionary" class="newWordDictionaryAction" method="saveWordDictionary">
			<result name="ajax" type="jsonmessage">
				<param name="message">message</param>
			</result>
		</action>
		
		
		<!-- 
			上传图片到server弹出页面
		 -->
		<action name="uploadImageDialog" class="newWordDictionaryAction" method="uploadImageDialog">
			<result name="success" type="tiles">uploadImageDialog</result>
		</action>
		
		<!-- 
			保存单词或词组到字典
		 -->
		<action name="uploadImageByAjax" class="newWordDictionaryAction" method="uploadImageByAjax">
			<result name="ajax" type="jsonmessage">
				<param name="message">message</param>
			</result>
		</action>
		
		<!-- 
			上传音频到server弹出页面
		 -->
		<action name="uploadAudioDialog" class="newWordDictionaryAction" method="uploadAudioDialog">
			<result name="success" type="tiles">uploadAudioDialog</result>
		</action>
		
		<!-- 
			上传音频
		 -->
		<action name="uploadAudioByAjax" class="newWordDictionaryAction" method="uploadAudioByAjax">
			<result name="ajax" type="jsonmessage">
				<param name="message">message</param>
			</result>
		</action>
		
		<!-- 
			根据ID和国家获取音频
		 -->
		<action name="getAudioByIdAndCountry" class="newWordDictionaryAction" method="getAudioByIdAndCountry">
			<result name="success" type="stream">  
               <param name="contentType">audio/mp3</param>  
               <param name="inputName">audioStream</param>  
               <param name="bufferSize">2048</param>  
            </result>
		</action>
		
		<!-- 
			根据Server端的文件获取音频
		 -->
		<action name="getAudioByFileName" class="newWordDictionaryAction" method="getAudioByFileName">
			<result name="success" type="stream">  
               <param name="contentType">audio/mp3</param>  
               <param name="inputName">audioStream</param>  
               <param name="bufferSize">2048</param>  
            </result>
		</action>
		
	</package>
</struts>

Action类

package com.wisemen.hhb.module.worddictionary.action;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import net.sf.json.JSONObject;
import org.apache.commons.io.FileUtils;
import com.wisemen.framework.server.action.BaseAction;
import com.wisemen.framework.server.exception.ActionException;
import com.wisemen.framework.util.StringUtils;
import com.wisemen.hhb.module.base.domain.WordDictionary;
import com.wisemen.hhb.module.base.vo.WordDictionaryVo;
import com.wisemen.hhb.module.worddictionary.biz.IWordDictionaryBiz;
import com.wisemen.hhb.module.worddictionary.util.WordDictionaryUtil;

public class WordDictionaryAction extends BaseAction {
	private static final long serialVersionUID = 1L;
	private static final String DEFAULT_WORD_IMG_PATH="images/word_default.png";
	private static final String COUNTRY_UK = "uk";
	private static final String COUNTRY_US = "us";
	
	/**
	 * 字典ID
	 */
	private String id;
	
	/**
	 * 单词或词组
	 */
	private String word;
	
	/**
	 * 字典Biz
	 */
	private IWordDictionaryBiz wordDictionaryBiz;

	/**rtmp服务器地址*/
	private String rtmpServerUrl;
	
	private ByteArrayInputStream imageStream;
	
	private ByteArrayInputStream audioStream;
	
	private Boolean useDefault = true;
	
	private WordDictionaryVo wordDictionaryVo;
	
	/**上传的图片文件*/
	private File file;
	
	/**文件名*/
    private String fileFileName;
    
    private String countryType;
    
    /**
     * 保存在Server端,音频的文件名
     */
    private String audioServerFileName;
    
	//------------------------------get/set--------------------------
	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}
	
	public String getWord() {
		return word;
	}

	public void setWord(String word) {
		this.word = word;
	}

	public IWordDictionaryBiz getWordDictionaryBiz() {
		return wordDictionaryBiz;
	}

	public void setWordDictionaryBiz(IWordDictionaryBiz wordDictionaryBiz) {
		this.wordDictionaryBiz = wordDictionaryBiz;
	}

	public String getRtmpServerUrl() {
		return rtmpServerUrl;
	}

	public void setRtmpServerUrl(String rtmpServerUrl) {
		this.rtmpServerUrl = rtmpServerUrl;
	}
	public ByteArrayInputStream getImageStream() {
		return imageStream;
	}

	public void setImageStream(ByteArrayInputStream imageStream) {
		this.imageStream = imageStream;
	}

	public Boolean getUseDefault() {
		return useDefault;
	}

	public void setUseDefault(Boolean useDefault) {
		this.useDefault = useDefault;
	}
	public WordDictionaryVo getWordDictionaryVo() {
		return wordDictionaryVo;
	}

	public void setWordDictionaryVo(WordDictionaryVo wordDictionaryVo) {
		this.wordDictionaryVo = wordDictionaryVo;
	}
	public File getFile() {
		return file;
	}

	public void setFile(File file) {
		this.file = file;
	}

	public String getFileFileName() {
		return fileFileName;
	}

	public void setFileFileName(String fileFileName) {
		this.fileFileName = fileFileName;
	}
	public ByteArrayInputStream getAudioStream() {
		return audioStream;
	}

	public void setAudioStream(ByteArrayInputStream audioStream) {
		this.audioStream = audioStream;
	}
	public String getCountryType() {
		return countryType;
	}

	public void setCountryType(String countryType) {
		this.countryType = countryType;
	}
	public String getAudioServerFileName() {
		return audioServerFileName;
	}

	public void setAudioServerFileName(String audioServerFileName) {
		this.audioServerFileName = audioServerFileName;
	}
	//------------------------------get/set--------------------------
	


	/**
	 * 进入单词编辑页
	 */
	public String editWordDictionary(){
		return SUCCESS;
	}
	
	/**
	 * 
	 * <p>Description:字典的图片</p>
	 * <p>Paramenter:</p>
	 * <p>Return:</p>
	 * <p>Exception:</p>
	 * <p>Modified History: </p>
	 */
	public String getImageById(){
		boolean useDefaultImage = false;
		WordDictionary wordDictionary = null;
		logger.debug("id is "+id);
		//判断id是否为空
		if(StringUtils.isEmpty(id)){
			useDefaultImage = true;
		}else{
			wordDictionary = wordDictionaryBiz.getWordDictionaryById(id);
		}
		
		if(null == wordDictionary || null == wordDictionary.getImage() ){
			useDefaultImage = true;
		}
		
		if(useDefaultImage == true && useDefault == true){
			String path = request.getSession().getServletContext().getRealPath("/");
			String imagePath = path + DEFAULT_WORD_IMG_PATH;
			logger.debug("default word imagePath : " + imagePath);
			try {
				imageStream = new ByteArrayInputStream(FileUtils.readFileToByteArray(new File(imagePath)));
			} catch (IOException e) {
				e.printStackTrace();
			}
		} else {
			imageStream = new ByteArrayInputStream(wordDictionary.getImage());
		}
		
		return SUCCESS;
	}
	
	/**
	 * 
	 * <p>Description:通过单词获取字典对象</p>
	 * <p>Paramenter:</p>
	 * <p>Return:</p>
	 * <p>Exception:</p>
	 * <p>Modified History: </p>
	 */
	public String getWordDictionaryByWord(){
		wordDictionaryVo = wordDictionaryBiz.getWordDictionaryByWord(word);
		return AJAX_RETURN_TYPE;
	}
	
	
	/**
	 * 
	 * <p>Description:保存单词到字典</p>
	 * <p>Paramenter:</p>
	 * <p>Return:</p>
	 * <p>Exception:</p>
	 * <p>Modified History: </p>
	 */
	public String saveWordDictionary(){
		boolean saveSuccess = true;
		String errorMsg = "";
		try{
			String contextPath = request.getSession().getServletContext().getRealPath("/");
			wordDictionaryBiz.saveWordDictionary(wordDictionaryVo, contextPath);
		}catch( Exception e){
			logger.error( "保存词典错误:" + e.getMessage() );
			saveSuccess = false;
			errorMsg = e.getMessage() ;
		}
		
		Map<String, Object> jsonMap = new HashMap<String,Object>();
		jsonMap.put("saveSuccess", saveSuccess);
		jsonMap.put("errorMsg", errorMsg);
		
		message = JSONObject.fromObject(jsonMap).toString();
		return AJAX_RETURN_TYPE;
	}
	
	/**
	 * 
	 * <p>Description:上传图片对话框</p>
	 * <p>Paramenter:</p>
	 * <p>Return:</p>
	 * <p>Exception:</p>
	 * <p>Modified History: </p>
	 */
	public String uploadImageDialog(){
		
		return SUCCESS;
	}
	
	/**
	 * 异步上传图片文件到Server
	 * @return
	 * @author ShiJiapeng
	 * @throws IOException 
	 */
	public String uploadImageByAjax() throws IOException{
		JSONObject json = new JSONObject();
		
		if(file == null || file.length() <= 0 || StringUtils.isEmpty(fileFileName)){
			json.put("success", false);
			json.put("message", "文件为空,请重新上传");
			message = json.toString();
			return AJAX_RETURN_TYPE;   
		}
		
		//获取文件后缀名
		String contextPath = request.getSession().getServletContext().getRealPath("/");
		String tempFileName = WordDictionaryUtil.createTempFileName(fileFileName);
		try{
			FileUtils.copyFile(file, new File(contextPath+ WordDictionaryUtil.TEMP_IMAGES_PATH+tempFileName));
		}catch( Exception e){
			logger.error( "上传图片错误:" + e.getMessage() );
			json.put("success", false);
			json.put("errorMsg", e.getMessage());
			message = json.toString();
			
			return AJAX_RETURN_TYPE;
		}
		
		json.put("success", true);
		json.put("imageName", tempFileName);
		message = json.toString();
		
		//防止IE下变成下载文件
		super.getServletResponse().setContentType("text/html");
		super.getServletResponse().getWriter().write(message);
		
		return null;
	}
	
	/**
	 * 
	 * <p>Description:上传图片对话框</p>
	 * <p>Paramenter:</p>
	 * <p>Return:</p>
	 * <p>Exception:</p>
	 * <p>Modified History: </p>
	 */
	public String uploadAudioDialog(){
		
		return SUCCESS;
	}
	
	/**
	 * 
	 * <p>Description:异步上传音频文件到Server</p>
	 * <p>Paramenter:</p>
	 * <p>Return:</p>
	 * <p>Exception:</p>
	 * <p>Modified History: </p>
	 */
	public String uploadAudioByAjax() throws IOException{
		JSONObject json = new JSONObject();
		
		if(file == null || file.length() <= 0 || StringUtils.isEmpty(fileFileName)){
			json.put("success", false);
			json.put("message", "文件为空,请重新上传");
			message = json.toString();
			return AJAX_RETURN_TYPE;   
		}
		
		//获取文件名
		String contextPath = request.getSession().getServletContext().getRealPath("/");
		String tempFileName = WordDictionaryUtil.createTempFileName(fileFileName);
		try{
			FileUtils.copyFile(file, new File(contextPath+ WordDictionaryUtil.TEMP_AUDIOS_PATH+tempFileName));
		}catch( Exception e){
			logger.error( "上传音频错误:" + e.getMessage() );
			json.put("success", false);
			json.put("errorMsg", e.getMessage());
			message = json.toString();
			
			return AJAX_RETURN_TYPE;
		}
		
		
		json.put("success", true);
		json.put("audioName", tempFileName);
		message = json.toString();
		logger.debug("message = " + message);
		
		//防止IE下变成下载文件
		super.getServletResponse().setContentType("text/html");
		super.getServletResponse().getWriter().write(message);
		
		return null;
	}
	
	/**
	 * 
	 * <p>Description:根据ID和[英式]or[美式]返回音频</p>
	 * <p>Paramenter:</p>
	 * <p>Return:</p>
	 * <p>Exception:</p>
	 * <p>Modified History: </p>
	 */
	public String getAudioByIdAndCountry(){
		WordDictionary wordDictionary = null;
		if( StringUtils.isEmpty(id) || StringUtils.isEmpty(countryType) ){
			throw new ActionException("args error.");
		}
		
		wordDictionary = wordDictionaryBiz.getWordDictionaryById(id);
		if(null == wordDictionary){
			audioStream = new ByteArrayInputStream(new byte[0]);
		}
		else{
			byte[] audioByteArray = null;
			if( COUNTRY_UK.equals(countryType) ){
				audioByteArray = wordDictionary.getUkAudioFile();
				if( audioByteArray == null ){
					audioStream = new ByteArrayInputStream(new byte[0]);
				}
				else{
					audioStream = new ByteArrayInputStream(audioByteArray);
				}
			}
			
			else if( COUNTRY_US.equals(countryType) ){
				audioByteArray = wordDictionary.getUsAudioFile();
				if( audioByteArray == null ){
					audioStream = new ByteArrayInputStream(new byte[0]);
				}
				else{
					audioStream = new ByteArrayInputStream(audioByteArray);
				}
			}
			
			else{
				throw new ActionException("countryType=" + countryType +", error.");
			}
		}
		
		return SUCCESS;
	}
	
	/**
	 * 
	 * <p>Description:根据Server端的音频文件,返回音频</p>
	 * <p>Paramenter:</p>
	 * <p>Return:</p>
	 * <p>Exception:</p>
	 * <p>Modified History: </p>
	 */
	public String getAudioByFileName(){
		if( StringUtils.isEmpty(audioServerFileName) ){
			throw new ActionException("args error.");
		}
		
		String contextPath = request.getSession().getServletContext().getRealPath("/");
		try {
			byte[] audioByteArray = FileUtils.readFileToByteArray( new File(contextPath+ WordDictionaryUtil.TEMP_AUDIOS_PATH +audioServerFileName) );
			audioStream = new ByteArrayInputStream(audioByteArray);
		} catch (IOException e) {
			audioStream = new ByteArrayInputStream(new byte[0]);
		}
		
		return SUCCESS;
	}
}



==========================================

图片上传弹出框jsp

<%@ page language="java" pageEncoding="UTF-8" contentType="text/html;charset=UTF-8"%>
<%@ include file="/common/taglibs.jsp"%>
<script language="javascript" type="text/javascript" src="<c:url value='/plugin/artDialog4.1.7/jquery.artDialog.js?skin=simple'/>"></script>
<script language="javascript" type="text/javascript" src="<c:url value='/plugin/artDialog4.1.7/plugins/iframeTools.js'/>"></script>
<script language= javascript  type= text/javascript  src="<c:url value='/default/scripts/jquery.form.js'/>" ></script>



<script type="text/javascript">
	
	
	$(document).ready(function(){
		var win = art.dialog.opener;//来源页面
		
		
		if (art.dialog.data('name')) {
			name=art.dialog.data('name');// 获取由主页面传递过来的数据
		};

		//上传图像
		$("#uploadbtn").click(function(){
			var filePath = $('#file').val();
			if(filePath==null || filePath== ''){
				alert('请选择要上传的文件');
				return;
			}
			else{
				var tempArray = filePath.split('\\');
				var index = tempArray.length-1;
				if(tempArray[index].length > 300){
					alert('文件名过长,请修改后重新上传');
					return;
				}
			}
			
			$('#uploadbtn').attr("disabled",true);
			$('#uploadbtn').attr("value","上传中...");
			
			$('#uploadForm').ajaxSubmit({		
				   
                   dataType: "json",
                   success: function (data){
			            var imageName = data.imageName;
			            if(imageName !=""){
						  	 win.changeImage(name,imageName);
							 art.dialog.close();
						}else{
							alert("上传失败,请重新上传");
						}
						
					$('#uploadbtn').attr("disabled",false);
					$('#uploadbtn').attr("value","上传");
			        }
   				});
		});

		$("#cancel").click(function(){
			art.dialog.close();
		});
	});
	

	
</script>	


<form id="uploadForm" action="<s:url value='/worddictionary/uploadImageByAjax.action'/>" method="post" enctype="multipart/form-data">
	<div style="text-align: center;margin-top: 20px;width: 100%;">
		<s:file name="file" size="20"  accept="image/*"  value="上传文件"></s:file>	
	</div>
	<div style="text-align: center;margin-top: 20px;width: 100%;" >
		<span>支持上传jpg、gif、png、bmp格式的图片,大小不超过4M	</span>
	</div>
</form>
<div style="width: 100%;text-align: right;margin-top: 20px;">
		<input id="uploadbtn"  type="button" class="button" value="上传" >
		<input id="cancel"  type="button" class="button" value="取消" style="margin-right:20px;">
</div>


音频上传弹出框jsp

<%@ page language="java" pageEncoding="UTF-8" contentType="text/html;charset=UTF-8"%>
<%@ include file="/common/taglibs.jsp"%>
<script language="javascript" type="text/javascript" src="<c:url value='/plugin/artDialog4.1.7/jquery.artDialog.js?skin=simple'/>"></script>
<script language="javascript" type="text/javascript" src="<c:url value='/plugin/artDialog4.1.7/plugins/iframeTools.js'/>"></script>
<script language= javascript  type= text/javascript  src="<c:url value='/default/scripts/jquery.form.js'/>" ></script>



<script type="text/javascript">
//选择上传文件后回调
$.onFileSelected = function(file){
	var filePath = $(file).val();
	
	if(filePath==null || filePath== ''){
		alert('请选择要上传的音频文件');
		return;
	}
	
	/**
	var speaker = $(file).nextAll(".speaker");
	var info = $(file).next("span");
	info.text("上传中...");

	$(file).parents("form").ajaxSubmit({
        dataType: "json",
        success: function (data){
	        if (data.success) {
	        	var audioId = data.audioId;
	        	var audioType = data.audioType;
	        	var audioName = data.audioName;
	        	info.text("");
	        	speaker.attr("audioId", audioId);
	        	speaker.attr("audioType", audioType);
	        	speaker.css("visibility", "visible");
	        } else {
	        	info.text("上传失败,请重新上传");
	        }
		}
	});
	**/
};
	
	$(document).ready(function(){
		var win = art.dialog.opener;//来源页面
		
		
		if (art.dialog.data('name')) {
			name=art.dialog.data('name');// 获取由主页面传递过来的数据
		};

		//上传图像
		$("#uploadbtn").click(function(){
			var filePath = $('#file').val();
			if(filePath==null || filePath== ''){
				alert('请选择要上传的文件');
				return;
			}
			else{
				var tempArray = filePath.split('\\');
				var index = tempArray.length-1;
				if(tempArray[index].length > 300){
					alert('文件名过长,请修改后重新上传');
					return;
				}
			}
			
			$('#uploadbtn').attr("disabled",true);
			$('#uploadbtn').attr("value","上传中...");
			
			$('#uploadForm').ajaxSubmit({		
				   
                   dataType: "json",
                   success: function (data){
			            var audioName = data.audioName;
			            if(audioName !=""){
						  	 win.changeAudio(name,audioName);
							 art.dialog.close();
						}else{
							alert("上传失败,请重新上传");
						}
						
					$('#uploadbtn').attr("disabled",false);
					$('#uploadbtn').attr("value","上传");
			        }
   				});
		});

		$("#cancel").click(function(){
			art.dialog.close();
		});
	});
	

	
</script>	


<form id="uploadForm" action="<s:url value='/worddictionary/uploadAudioByAjax.action'/>" method="post" enctype="multipart/form-data">
	<div style="text-align: center;margin-top: 20px;width: 100%;">
		<input id="file" name="file" accept="audio/mp3" type="file" οnchange="$.onFileSelected(this)">
	</div>
	<div style="text-align: center;margin-top: 20px;width: 100%;" >
		<span>支持上传mp3格式的音频,大小不超过4M	</span>
	</div>
</form>

<div style="width: 100%;text-align: right;margin-top: 20px;">
		<input id="uploadbtn"  type="button" class="button" value="上传" >
		<input id="cancel"  type="button" class="button" value="取消" style="margin-right:20px;">
</div>





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值