上传图片和音频到DB

jsp页面

<%@ page language="java" pageEncoding="UTF-8" contentType="text/html;charset=UTF-8"%>
<%@ include file="/common/taglibs.jsp"%>
<%@ include file="/pages/exercise/editExerciseFrame.jsp"%>
<script language= javascript  type= text/javascript  src="<c:url value='/default/scripts/jquery.form.js'/>" ></script>
	
<style type="text/css">

#container{
clear:both;
width:100%;
height:400px;
}

/***一下为新添加***/
.font-16{
	font-family: 微软雅黑;
	font-size: 16px;
	font-weight: bold;
	font-style: normal;
	text-decoration: none;
	color: #999999;
}


table#table2 tr{
	height: 45px;
}

table#table2 tr td{
/**
	border: 1px solid #888;
	**/
}

table#table2 tr td:FIRST-CHILD{
	text-align: right;
}

table#table2{

	border-collapse:collapse;
	border-spacing:0;

}
.speaker {
	background-position: -90px 0px;
}

.icon-button {
	display: inline-block;
	zoom: 1;
	vertical-align: baseline;
	margin: 0 2px;
	outline: none;
	cursor: pointer;
	padding: 0px;
	width: 20px;
	height: 20px;
	border: solid 0px #fff;
	background: url('<c:url value="/images/control_all_btn.png"/>') no-repeat scroll 0px 0px;
}
</style>


<!-- 中间独立的部分 -->

<script type="text/javascript">
//根据题目序号获取中间部分内容
$.getMiddleContent = function(index,itemObj){
	var content = $("#middleContent").clone();
	content.attr("id", "middleContent" + index);
	

	
	if(itemObj != null){

		var question = itemObj.question;
		var audioObj = content.find(".speaker");
		audioObj.attr("audioId", question)
		audioObj.css("visibility", "visible");
		
		var answerArray = itemObj.answer.split(",");
		for(var i=0; i<answerArray.length; i++ ){
			var imageId = answerArray[i].split("_")[1];
			content.find("#img_" + (i+1)).attr("src","<s:url value='/imagehandler/getImageById.action?id='/>"+imageId);
			content.find("#img_" + (i+1)).attr("imageId",imageId);
		}

	}
	
	//播放器触发
	content.find(".speaker").click(function(){
		var audioId = $(this).attr("audioId");
		var audioType = $(this).attr("audioType");
		if (audioId) {
			var audioUrl = "audio/" + audioId + "." + audioType;
			thisMovie("editExerciseAudioPlayer").loadAndPlayAudio(audioUrl);
		}
	});
	return content;
	
};
//检查数据完整性
$.checkEditContent = function(){
	return true;
};

//获取用户编辑后的信息
$.getEditContent = function(){
	var itemArray  = new Array();
	$(".exercise_item_container").each(function(){
		var sentenceArray  = new Array();
		
		//question保存音频ID
		var question = $(this).find(".speaker").attr("audioId");
		
		var answer = "";
		//answer保存(序号_图片ID)
		for( var i=1; i<=6; i++ ){
			var imgObj = $("#img_" + i);
			if( imgObj.attr("imageId") == "" ){
				break;
			}
			answer = answer + i + "_" + imgObj.attr("imageId")+",";
		}
		
		answer = answer.substring(0, answer.length-1);
		
		if(question!=""&&answer!=""){
			itemArray.push( {"question": question, "answer": answer});
		}			
		
	});

	return itemArray;
};

//选择上传文件后回调
$.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("上传失败,请重新上传");
	        }
		}
	});
};

//选择上传文件后回调
$.onImgFileSelected = function(file){
	var filePath = $(file).val();
	
	if(filePath==null || filePath== ''){
		alert('请选择要上传的图片文件');
		return;
	}
	
	var image = $(file).parents("td").next("td").find("img");
	var info = $(file).next("span");
	info.text("上传中...");
	$(file).parents("form").ajaxSubmit({
        dataType: "json",
        success: function (data){
       		var imageId = data.imageId;
	        if (imageId !="") {
	        	image.attr("src","<s:url value='/imagehandler/getImageById.action?id='/>"+imageId);
	        	image.attr("imageId",imageId);
	        	info.text("");
	        } else {
	        	info.text("上传失败,请重新上传");
	        }
				},
				error:function(){
					info.text("上传失败,请重新上传");
				}
	});
};

$().ready(function(){
	
	$("input .icon-button").hover(function(){
		$(this).attr("background-position", "-90px -30px")
	},
	function(){
		$(this).attr("background-position", "-90px 0px")
	});
	
});

//flash播放器加载完回调
function onPlayerCompleted(){
	//与流媒体服务器建立连接
	
	var rtmpServerUrl = "${rtmpServerUrl}";
	console.info(rtmpServerUrl);
	thisMovie("editExerciseAudioPlayer").setRtmpServerURL(rtmpServerUrl);
}

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="editExerciseAudioPlayer" id="editExerciseAudioPlayer" >
	<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>

<div style="display: none;">
	<div id="middleContent">
		<div>
			<span class="font-16">上传录音且按顺序上传3-6张相关图片!</span>
		</div>

		<table id="table2" style="margin-left: 20px;margin-top: 10px;">
			<tr>
				<td>音频文件:</td>
				<td>
					<form action="<c:url value='/audiohandler/uploadByAjax.action'/>" method="post" enctype="multipart/form-data">
						<input id="uploadAudio" name="file" accept="audio/mp3" type="file" onchange="$.onFileSelected(this)">
						<span class="font-12"></span>
						<input class="icon-button speaker" audioId="" audioType="mp3" type="button" style="visibility: hidden;">
					</form>
				</td>
				<td></td>
			</tr>
			<tr>
				<td>1.</td>
				<td>
					<form id="01" action="<s:url value='/admin/uploadImage.action'/>" method="post" enctype="multipart/form-data">
						<input id="uploadImg_01" name="file" accept="image/*" type="file" onchange="$.onImgFileSelected(this)">
						<span class="font-12"></span>
					</form>
				</td>
				<td><img id="img_1" class="wordImg"  width="45px" height="45px" imageId=""/></td>
			</tr>
			<tr>
				<td>2.</td>
				<td>
					<form id="02" action="<s:url value='/admin/uploadImage.action'/>" method="post" enctype="multipart/form-data">
						<input id="uploadImg_02" name="file" accept="image/*" type="file" onchange="$.onImgFileSelected(this)">
						<span class="font-12"></span>
					</form>
				</td>
				<td><img id="img_2" class="wordImg"  width="45px" height="45px" imageId=""/></td>
			</tr>
			<tr>
				<td>3.</td>
				<td>
					<form id="03" action="<s:url value='/admin/uploadImage.action'/>" method="post" enctype="multipart/form-data">
						<input id="uploadImg_03" name="file" accept="image/*" type="file" onchange="$.onImgFileSelected(this)">
						<span class="font-12"></span>
					</form>
				</td>
				<td><img id="img_3" class="wordImg"  width="45px" height="45px" imageId=""/></td>
			</tr>
			<tr>
				<td>4.</td>
				<td>
					<form id="04" action="<s:url value='/admin/uploadImage.action'/>" method="post" enctype="multipart/form-data">
						<input id="uploadImg_04" name="file" accept="image/*" type="file" onchange="$.onImgFileSelected(this)">
						<span class="font-12"></span>
					</form>
				</td>
				<td><img id="img_4" class="wordImg"  width="45px" height="45px" imageId=""/></td>
			</tr>
			<tr>
				<td>5.</td>
				<td>
					<form id="05" action="<s:url value='/admin/uploadImage.action'/>" method="post" enctype="multipart/form-data">
						<input id="uploadImg_05" name="file" accept="image/*" type="file" onchange="$.onImgFileSelected(this)">
						<span class="font-12"></span>
					</form>
				</td>
				<td><img id="img_5" class="wordImg"  width="45px" height="45px" imageId=""/></td>
			</tr>
			<tr>
				<td>6.</td>
				<td>
					<form id="06" action="<s:url value='/admin/uploadImage.action'/>" method="post" enctype="multipart/form-data">
						<input id="uploadImg_06" name="file" accept="image/*" type="file" onchange="$.onImgFileSelected(this)">
						<span class="font-12"></span>
					</form>
				</td>
				<td><img id="img_6" class="wordImg"  width="45px" height="45px" imageId=""/></td>
			</tr>
		</table>
		
	</div>
</div>


图片上传Action

<?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="imagehandler" namespace="/imagehandler" extends="web-default">
		<!--
			根据id获取图片
		-->
		<action name="getImageById" class="imageHandlerAction" 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="uploadByAjax" class="imageHandlerAction" method="uploadByAjax">
			<result name="ajax" type="jsonmessage">
				<param name="message">message</param>
			</result>
		</action>

	</package>

</struts>

图片上传类

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

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;

import net.sf.json.JSONObject;

import org.apache.commons.io.FileUtils;

import com.wisemen.framework.server.action.BaseAction;
import com.wisemen.framework.util.StringUtils;
import com.wisemen.hhb.module.base.domain.Image;
import com.wisemen.hhb.module.imagehandler.service.IImageHandlerService;

public class ImageHandlerAction extends BaseAction{

	/**
	 * 
	 */
	private static final String DEFAULT_PICTURE_PATH="images/default_picture.jpg";
	
	private static final long serialVersionUID = -1163017407936568957L;
	
	private ByteArrayInputStream imageStream;
	
	private String id;
	
	private Boolean useDefault = true;
	
	private IImageHandlerService imageHandlerService;
	
	/**上传的图片文件*/
	private File file;
	
	/**文件名*/
    private String fileFileName;
	/*===============================================Getters and Setters Start============================================*/

	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 String getId() {
		return id;
	}


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


	public IImageHandlerService getImageHandlerService() {
		return imageHandlerService;
	}


	public void setImageHandlerService(IImageHandlerService imageHandlerService) {
		this.imageHandlerService = imageHandlerService;
	}
	
	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;
	}
	/*===============================================Getters and Setters Start============================================*/
	

	/**
	 * <p>description:根据id获得图像</p>
	 * <p>author:朱建林</p>
	 * <p>time:2013-8-01</p>
	 */
	public String getImageById(){
		boolean useDefaultImage = false;
		Image image = null;
		logger.debug("id is "+id);
		//判断id是否为空
		if(StringUtils.isEmpty(id)){
			useDefaultImage = true;
		}else{
			 image = imageHandlerService.getImageById(id);
		}
		
		if(null == image || null == image.getContent()){
			useDefaultImage = true;
		}
		
		if(useDefaultImage == true && useDefault == true){
			String path = request.getSession().getServletContext().getRealPath("/");
			String imagePath = path + DEFAULT_PICTURE_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(image.getContent());
		}
		
		return SUCCESS;
	}


	/**
	 * 异步上传图片文件
	 * @return
	 * @author ShiJiapeng
	 * @throws IOException 
	 */
	public String uploadByAjax() 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 type = "";
		int index = fileFileName.lastIndexOf(".");
		if(index >= 0){
			 type =  fileFileName.substring(index+1);
		}

		byte[] imageByte = FileUtils.readFileToByteArray(file);
		String id = imageHandlerService.saveImage(imageByte, type);
		
		json.put("success", true);
		json.put("imageId", id);
		json.put("imageType", type);
		json.put("imageName", fileFileName);
		message = json.toString();
		
		//防止IE下变成下载文件
		super.getServletResponse().setContentType("text/html");
		super.getServletResponse().getWriter().write(message);
		
		return null;
	}
	
}

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

音频上传Action

<?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="audiohandler" namespace="/audiohandler" extends="web-default">
		<!--
			根据id获取音频
		-->
		<action name="getAudioById" class="audioHandlerAction" method="getAudioById">
			<result name="success" type="stream">  
               <param name="contentType">audio/mp3</param>  
               <param name="inputName">audioStream</param>  
               <param name="bufferSize">2048</param>  
            </result>
		</action>
		
		<!-- 
			上传音频
		 -->
		<action name="uploadByAjax" class="audioHandlerAction" method="uploadByAjax">
			<result name="ajax" type="jsonmessage">
				<param name="message">message</param>
			</result>
		</action>

	</package>

</struts>

音频上传类

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

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;

import org.apache.commons.io.FileUtils;

import net.sf.json.JSONObject;

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.audiohandler.service.IAudioHandlerService;
import com.wisemen.hhb.module.base.domain.Audio;

public class AudioHandlerAction extends BaseAction{

	private static final long serialVersionUID = -9087644531038401978L;
	
	private IAudioHandlerService audioHandlerService;
	
	private ByteArrayInputStream audioStream;
	
	private String id;
	
	/**上传的音频文件*/
	private File file;
	
	/**文件名*/
    private String fileFileName;
	
	/*===============================================Getters and Setters Start============================================*/

	public ByteArrayInputStream getAudioStream() {
		return audioStream;
	}

	public IAudioHandlerService getAudioHandlerService() {
		return audioHandlerService;
	}

	public void setAudioHandlerService(IAudioHandlerService audioHandlerService) {
		this.audioHandlerService = audioHandlerService;
	}

	public void setAudioStream(ByteArrayInputStream audioStream) {
		this.audioStream = audioStream;
	}

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}
	
	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;
	}

	/*===============================================Getters and Setters Start============================================*/
	/**
	 * <p>description:根据id获得音频</p>
	 * <p>author:朱建林</p>
	 * <p>time:2013-8-01</p>
	 */
	public String getAudioById(){
		Audio audio = null;
		boolean useDefaultImage = false;
		if(StringUtils.isEmpty(id)){
			useDefaultImage = true;
			logger.debug("the id of audio is null");
			throw new ActionException("系统错误");
		}else{
			audio = audioHandlerService.getAudioById(id);
		}
		
		if(null == audio || null == audio.getContent()){
			useDefaultImage = true;
			logger.debug("the audio is null");
			throw new ActionException("系统错误");
		}
		if(useDefaultImage == false){
			audioStream = new ByteArrayInputStream(audio.getContent());
		}
		
		return SUCCESS;
	}
	
	/**
	 * 异步上传音频文件
	 * @return
	 * @author ShiJiapeng
	 * @throws IOException 
	 */
	public String uploadByAjax() 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 type = "";
		int index = fileFileName.lastIndexOf(".");
		if(index >= 0){
			 type =  fileFileName.substring(index+1);
		}

		byte[] audioByte = FileUtils.readFileToByteArray(file);
		String audioId = audioHandlerService.saveAudio(audioByte, type);
		
		json.put("success", true);
		json.put("audioId", audioId);
		json.put("audioType", type);
		json.put("audioName", fileFileName);
		message = json.toString();
		logger.debug("message = " + message);
		
		//防止IE下变成下载文件
		super.getServletResponse().setContentType("text/html");
		super.getServletResponse().getWriter().write(message);
		
		return null;
	}

}





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值