java,jsp,javabean:怎么实现上传图像?
例如在A.jsp中有的一个form中有<inputtype='file'name='xxx'id='xxx'>,然后被提交到B.jsp中,在B.jsp中用一个<jsp:u...
例如在A.jsp中有的一个form中有<input type='file' name='xxx' id='xxx'>,然后被提交到B.jsp中,在B.jsp中用一个<jsp:useBean id='xxxxxx' scope='page' class='xxxxx.xxxxx.xxxx'>来实现讲传过来这张图片存在主机的某个文件夹中。
【问题是】
在B.jsp中用<jsp:setProperty property='xxx' param='xxx'>来获得,但javabean里要怎么写才能接受这个图像呢?用Image img=new Image()?
---------------------------------------------------------------------------------
希望高手说的详细些,非常感谢! 展开
【问题是】
在B.jsp中用<jsp:setProperty property='xxx' param='xxx'>来获得,但javabean里要怎么写才能接受这个图像呢?用Image img=new Image()?
---------------------------------------------------------------------------------
希望高手说的详细些,非常感谢! 展开
2个回答
展开全部
呵呵 我刚做了个异步上传图片的功能 代码原封不动的给你发过来 ;
upload.jsp------------------------------------
<%@ page language="java" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<html>
<head>
<title>文件上传</title>
<link rel="stylesheet" type="text/css"
href="<%=basePath%>/style/css/style.css">
<Script TYPE="text/javascript" src="<%=basePath%>/common/js/jquery.min.js"></Script>
<script type="text/javascript"
src="<%=basePath%>/common/js/ajaxfileupload.js"></script>
<script type="text/javascript">
var bathPath= "/" + window.document.location.pathname.split("/")[1]+"/";
var divId=getParam("divId");
var componentName=getParam("componentName");
var photoSrc=getParam("photoSrc");
jQuery(document).ready(function(){
if(photoSrc!=null&&photoSrc!=""){
jQuery("<div><image src=\"" + photoSrc + "\" height='80px' /></div>").appendTo("#img");
}
}
)
function getParam(param){
var url=window.location.href;
var paramUrl = url.substr(url.indexOf("?")+1,url.length).replace("#","");
var arrParam = paramUrl.split("&");
for(var i = 0; i<arrParam.length; i++){
if(arrParam[i].split("=")[0] == param){
return arrParam[i].split("=")[1];
}
}
}
function upload(){
$.ajaxFileUpload({
url:'uploadphoto.action', //需要链接到服务器地址
secureuri:false,
fileElementId:'fileid', //文件选择框的id属性
dataType: 'text', //服务器返回的格式,可以是json
success: function (result, status) //相当于java中try语句块的用法
{ //data是从服务器返回来的值
if(result=="false"){
alert("上传失败");
}
else{
alert("上传成功");
$("#img").empty();
var src=bathPath+result;
$("<div><image src=\"" + src + "\" height='80px' /></div>").appendTo("#img");
}
jQuery("#"+divId,window.parent.document).empty();
jQuery("#"+divId,window.parent.document).append("<input type='hidden' id='dddddd' value=" + result +" name=" + componentName +" ");
}
}
);
}
var jpgFile = true;
function getFileName(obj) {
var posStart = obj.value.lastIndexOf("\\") * 1;
var posEnd = obj.value.lastIndexOf(".") * 1;
return obj.value.substring(posStart + 1, posEnd);
}
function getFileExt(obj) {
var posEnd = obj.value.lastIndexOf(".") * 1;
return obj.value.substring(posEnd + 1);
}
function getFFFileName() {
var allName = document.getElementById('fileid').value;
var posStart = "";
var posEnd = allName.lastIndexOf(".") * 1;
return allName.substring(posStart, posEnd);
}
function getFFFileExt() {
var allName = document.getElementById('fileid').value;
var posEnd = allName.lastIndexOf(".") * 1;
return allName.substring(posEnd + 1);
}
function ifJpgFile(obj) {
var filename;
var fileext;
if (window.navigator.userAgent.indexOf("MSIE") >= 1) {
filename = getFileName(obj);
fileext = getFileExt(obj);
} else if (window.navigator.userAgent.indexOf("Firefox") >= 1) {
filename = getFFFileName();
fileext = getFFFileExt();
}
var fileType = document.getElementById('fileid').value;
var lastIndexOfDot = fileType.lastIndexOf('.');
fileType = fileType.substr(lastIndexOfDot).toLowerCase();
if (fileType != '.jpg'&& fileType != '.jpeg'&& fileType != '.gif'&& fileType != '.bmp'&&fileType != '.png'&&fileType != '.tif') {
jpgFile = false;
} else {
jpgFile = true;
}
}
function chk() {
if (document.getElementById('fileid').value == '') {
alert('请选择要上传的文件!');
return false;
} else if (jpgFile) {
upload();
} else {
alert('请上传图片文件!');
}
}
</script>
</head>
<body>
<div id="img"></div>
文件:
<input id="fileid" size="10" type="file" name="zip" onchange="ifJpgFile(this)">
<br>
<input type="button" value="上传" onclick="chk()" />
</body>
</html>
ajaxfileupload.js--------------------------------------------
// JavaScript Document
jQuery.extend({
createUploadIframe: function(id, uri)
{
//create frame
var frameId = 'jUploadFrame' + id;
if(window.ActiveXObject) {
var io = document.createElement('<iframe id="' + frameId + '" name="' + frameId + '" />');
if(typeof uri== 'boolean'){
io.src = 'javascript:false';
}
else if(typeof uri== 'string'){
io.src = uri;
}
}
else {
var io = document.createElement('iframe');
io.id = frameId;
io.name = frameId;
}
io.style.position = 'absolute';
io.style.top = '-1000px';
io.style.left = '-1000px';
document.body.appendChild(io);
return io;
},
createUploadForm: function(id, fileElementId)
{
//create form
var formId = 'jUploadForm' + id;
var fileId = 'jUploadFile' + id;
var form = jQuery('<form action="" method="POST" name="' + formId + '" id="' + formId + '" enctype="multipart/form-data"></form>');
var oldElement = jQuery('#' + fileElementId);
var newElement = jQuery(oldElement).clone();
jQuery(oldElement).attr('id', fileId);
jQuery(oldElement).before(newElement);
jQuery(oldElement).appendTo(form);
//set attributes
jQuery(form).css('position', 'absolute');
jQuery(form).css('top', '-1200px');
jQuery(form).css('left', '-1200px');
jQuery(form).appendTo('body');
return form;
},
ajaxFileUpload: function(s) {
// TODO introduce global settings, allowing the client to modify them for all requests, not only timeout
s = jQuery.extend({}, jQuery.ajaxSettings, s);
var id = s.fileElementId;
var form = jQuery.createUploadForm(id, s.fileElementId);
var io = jQuery.createUploadIframe(id, s.secureuri);
var frameId = 'jUploadFrame' + id;
var formId = 'jUploadForm' + id;
if( s.global && ! jQuery.active++ )
{
// Watch for a new set of requests
jQuery.event.trigger( "ajaxStart" );
}
var requestDone = false;
// Create the request object
var xml = {};
if( s.global )
{
jQuery.event.trigger("ajaxSend", [xml, s]);
}
var uploadCallback = function(isTimeout)
{
// Wait for a response to come back
var io = document.getElementById(frameId);
try
{
if(io.contentWindow)
{
xml.responseText = io.contentWindow.document.body?io.contentWindow.document.body.innerHTML:null;
xml.responseXML = io.contentWindow.document.XMLDocument?io.contentWindow.document.XMLDocument:io.contentWindow.document;
}else if(io.contentDocument)
{
xml.responseText = io.contentDocument.document.body?io.contentDocument.document.body.innerHTML:null;
xml.responseXML = io.contentDocument.document.XMLDocument?io.contentDocument.document.XMLDocument:io.contentDocument.document;
}
}catch(e)
{
jQuery.handleError(s, xml, null, e);
}
if( xml || isTimeout == "timeout")
{
requestDone = true;
var status;
try {
status = isTimeout != "timeout" ? "success" : "error";
// Make sure that the request was successful or notmodified
if( status != "error" )
{
// process the data (runs the xml through httpData regardless of callback)
var data = jQuery.uploadHttpData( xml, s.dataType );
if( s.success )
{
// ifa local callback was specified, fire it and pass it the data
s.success( data, status );
};
if( s.global )
{
// Fire the global callback
jQuery.event.trigger( "ajaxSuccess", [xml, s] );
};
} else
{
jQuery.handleError(s, xml, status);
}
} catch(e)
{
status = "error";
jQuery.handleError(s, xml, status, e);
};
if( s.global )
{
// The request was completed
jQuery.event.trigger( "ajaxComplete", [xml, s] );
};
// Handle the global AJAX counter
if(s.global && ! --jQuery.active)
{
jQuery.event.trigger("ajaxStop");
};
if(s.complete)
{
s.complete(xml, status);
} ;
jQuery(io).unbind();
setTimeout(function()
{ try
{
jQuery(io).remove();
jQuery(form).remove();
} catch(e)
{
jQuery.handleError(s, xml, null, e);
}
}, 100);
xml = null;
};
}
// Timeout checker
if( s.timeout > 0 )
{
setTimeout(function(){
if( !requestDone )
{
// Check to see ifthe request is still happening
uploadCallback( "timeout" );
}
}, s.timeout);
}
try
{
var form = jQuery('#' + formId);
jQuery(form).attr('action', s.url);
jQuery(form).attr('method', 'POST');
jQuery(form).attr('target', frameId);
if(form.encoding)
{
form.encoding = 'multipart/form-data';
}
else
{
form.enctype = 'multipart/form-data';
}
jQuery(form).submit();
} catch(e)
{
jQuery.handleError(s, xml, null, e);
}
if(window.attachEvent){
document.getElementById(frameId).attachEvent('onload', uploadCallback);
}
else{
document.getElementById(frameId).addEventListener('load', uploadCallback, false);
}
return {abort: function () {}};
},
uploadHttpData: function( r, type ) {
var data = !type;
data = type == "xml" || data ? r.responseXML : r.responseText;
// ifthe type is "script", eval it in global context
if( type == "script" )
{
jQuery.globalEval( data );
}
// Get the JavaScript object, ifJSON is used.
if( type == "json" )
{
eval( "data = " + data );
}
// evaluate scripts within html
if( type == "html" )
{
jQuery("<div>").html(data).evalScripts();
}
return data;
}
});
upload.action------------------------------------------
package com.tjopen.define.action;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.tjopen.base.util.Util;
@SuppressWarnings("serial")
public class UploadAction extends ActionSupport {
private File zip;
private String zipFileName;
private String realpath;
private String filePath;
public void uploadphoto(){
HttpServletResponse response = ServletActionContext.getResponse();
response.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
// 保存到项目的路径下
String basePath = ServletActionContext.getServletContext().getRealPath("/");
SimpleDateFormat formater = new SimpleDateFormat("yyyy-M-dd");
String middlePath = "resources/photo/" + formater.format(new Date());
String tempMiddlePath = "";
// 生成时间戳文件夹路径
String str = "";
for (int i = 1; i < 100000; i++) {
tempMiddlePath = middlePath + "_" + i + "/";
str = middlePath + "_" + (i - 1 < 1 ? 1 : i - 1) + "/";
File parentDir = new File(basePath + tempMiddlePath);
if (parentDir.exists()) {
continue;
} else {
parentDir = new File(basePath + str);
if (parentDir != null && parentDir.list() != null && parentDir.list().length < 200) {
middlePath = str;
} else {
middlePath = tempMiddlePath;
}
break;
}
}
// 保存文件名
String filename=zipFileName;
String savefilePath=basePath+middlePath+filename;
File savefile = new File(savefilePath);
String result=middlePath+filename;
if(zip!= null){
try {
FileUtils.copyFile(zip, savefile);
} catch (IOException e) {
result="false";
}
}
else{
result="false";
}
try {
response.getWriter().print(result);
} catch (IOException e) {
e.printStackTrace();
}
}
public File getZip() {
return zip;
}
public void setZip(File zip) {
this.zip = zip;
}
public String getZipFileName() {
return zipFileName;
}
public void setZipFileName(String zipFileName) {
this.zipFileName = zipFileName;
}
public String getFilePath() {
return filePath;
}
public void setFilePath(String filePath) {
this.filePath = filePath;
}
}
upload.jsp------------------------------------
<%@ page language="java" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<html>
<head>
<title>文件上传</title>
<link rel="stylesheet" type="text/css"
href="<%=basePath%>/style/css/style.css">
<Script TYPE="text/javascript" src="<%=basePath%>/common/js/jquery.min.js"></Script>
<script type="text/javascript"
src="<%=basePath%>/common/js/ajaxfileupload.js"></script>
<script type="text/javascript">
var bathPath= "/" + window.document.location.pathname.split("/")[1]+"/";
var divId=getParam("divId");
var componentName=getParam("componentName");
var photoSrc=getParam("photoSrc");
jQuery(document).ready(function(){
if(photoSrc!=null&&photoSrc!=""){
jQuery("<div><image src=\"" + photoSrc + "\" height='80px' /></div>").appendTo("#img");
}
}
)
function getParam(param){
var url=window.location.href;
var paramUrl = url.substr(url.indexOf("?")+1,url.length).replace("#","");
var arrParam = paramUrl.split("&");
for(var i = 0; i<arrParam.length; i++){
if(arrParam[i].split("=")[0] == param){
return arrParam[i].split("=")[1];
}
}
}
function upload(){
$.ajaxFileUpload({
url:'uploadphoto.action', //需要链接到服务器地址
secureuri:false,
fileElementId:'fileid', //文件选择框的id属性
dataType: 'text', //服务器返回的格式,可以是json
success: function (result, status) //相当于java中try语句块的用法
{ //data是从服务器返回来的值
if(result=="false"){
alert("上传失败");
}
else{
alert("上传成功");
$("#img").empty();
var src=bathPath+result;
$("<div><image src=\"" + src + "\" height='80px' /></div>").appendTo("#img");
}
jQuery("#"+divId,window.parent.document).empty();
jQuery("#"+divId,window.parent.document).append("<input type='hidden' id='dddddd' value=" + result +" name=" + componentName +" ");
}
}
);
}
var jpgFile = true;
function getFileName(obj) {
var posStart = obj.value.lastIndexOf("\\") * 1;
var posEnd = obj.value.lastIndexOf(".") * 1;
return obj.value.substring(posStart + 1, posEnd);
}
function getFileExt(obj) {
var posEnd = obj.value.lastIndexOf(".") * 1;
return obj.value.substring(posEnd + 1);
}
function getFFFileName() {
var allName = document.getElementById('fileid').value;
var posStart = "";
var posEnd = allName.lastIndexOf(".") * 1;
return allName.substring(posStart, posEnd);
}
function getFFFileExt() {
var allName = document.getElementById('fileid').value;
var posEnd = allName.lastIndexOf(".") * 1;
return allName.substring(posEnd + 1);
}
function ifJpgFile(obj) {
var filename;
var fileext;
if (window.navigator.userAgent.indexOf("MSIE") >= 1) {
filename = getFileName(obj);
fileext = getFileExt(obj);
} else if (window.navigator.userAgent.indexOf("Firefox") >= 1) {
filename = getFFFileName();
fileext = getFFFileExt();
}
var fileType = document.getElementById('fileid').value;
var lastIndexOfDot = fileType.lastIndexOf('.');
fileType = fileType.substr(lastIndexOfDot).toLowerCase();
if (fileType != '.jpg'&& fileType != '.jpeg'&& fileType != '.gif'&& fileType != '.bmp'&&fileType != '.png'&&fileType != '.tif') {
jpgFile = false;
} else {
jpgFile = true;
}
}
function chk() {
if (document.getElementById('fileid').value == '') {
alert('请选择要上传的文件!');
return false;
} else if (jpgFile) {
upload();
} else {
alert('请上传图片文件!');
}
}
</script>
</head>
<body>
<div id="img"></div>
文件:
<input id="fileid" size="10" type="file" name="zip" onchange="ifJpgFile(this)">
<br>
<input type="button" value="上传" onclick="chk()" />
</body>
</html>
ajaxfileupload.js--------------------------------------------
// JavaScript Document
jQuery.extend({
createUploadIframe: function(id, uri)
{
//create frame
var frameId = 'jUploadFrame' + id;
if(window.ActiveXObject) {
var io = document.createElement('<iframe id="' + frameId + '" name="' + frameId + '" />');
if(typeof uri== 'boolean'){
io.src = 'javascript:false';
}
else if(typeof uri== 'string'){
io.src = uri;
}
}
else {
var io = document.createElement('iframe');
io.id = frameId;
io.name = frameId;
}
io.style.position = 'absolute';
io.style.top = '-1000px';
io.style.left = '-1000px';
document.body.appendChild(io);
return io;
},
createUploadForm: function(id, fileElementId)
{
//create form
var formId = 'jUploadForm' + id;
var fileId = 'jUploadFile' + id;
var form = jQuery('<form action="" method="POST" name="' + formId + '" id="' + formId + '" enctype="multipart/form-data"></form>');
var oldElement = jQuery('#' + fileElementId);
var newElement = jQuery(oldElement).clone();
jQuery(oldElement).attr('id', fileId);
jQuery(oldElement).before(newElement);
jQuery(oldElement).appendTo(form);
//set attributes
jQuery(form).css('position', 'absolute');
jQuery(form).css('top', '-1200px');
jQuery(form).css('left', '-1200px');
jQuery(form).appendTo('body');
return form;
},
ajaxFileUpload: function(s) {
// TODO introduce global settings, allowing the client to modify them for all requests, not only timeout
s = jQuery.extend({}, jQuery.ajaxSettings, s);
var id = s.fileElementId;
var form = jQuery.createUploadForm(id, s.fileElementId);
var io = jQuery.createUploadIframe(id, s.secureuri);
var frameId = 'jUploadFrame' + id;
var formId = 'jUploadForm' + id;
if( s.global && ! jQuery.active++ )
{
// Watch for a new set of requests
jQuery.event.trigger( "ajaxStart" );
}
var requestDone = false;
// Create the request object
var xml = {};
if( s.global )
{
jQuery.event.trigger("ajaxSend", [xml, s]);
}
var uploadCallback = function(isTimeout)
{
// Wait for a response to come back
var io = document.getElementById(frameId);
try
{
if(io.contentWindow)
{
xml.responseText = io.contentWindow.document.body?io.contentWindow.document.body.innerHTML:null;
xml.responseXML = io.contentWindow.document.XMLDocument?io.contentWindow.document.XMLDocument:io.contentWindow.document;
}else if(io.contentDocument)
{
xml.responseText = io.contentDocument.document.body?io.contentDocument.document.body.innerHTML:null;
xml.responseXML = io.contentDocument.document.XMLDocument?io.contentDocument.document.XMLDocument:io.contentDocument.document;
}
}catch(e)
{
jQuery.handleError(s, xml, null, e);
}
if( xml || isTimeout == "timeout")
{
requestDone = true;
var status;
try {
status = isTimeout != "timeout" ? "success" : "error";
// Make sure that the request was successful or notmodified
if( status != "error" )
{
// process the data (runs the xml through httpData regardless of callback)
var data = jQuery.uploadHttpData( xml, s.dataType );
if( s.success )
{
// ifa local callback was specified, fire it and pass it the data
s.success( data, status );
};
if( s.global )
{
// Fire the global callback
jQuery.event.trigger( "ajaxSuccess", [xml, s] );
};
} else
{
jQuery.handleError(s, xml, status);
}
} catch(e)
{
status = "error";
jQuery.handleError(s, xml, status, e);
};
if( s.global )
{
// The request was completed
jQuery.event.trigger( "ajaxComplete", [xml, s] );
};
// Handle the global AJAX counter
if(s.global && ! --jQuery.active)
{
jQuery.event.trigger("ajaxStop");
};
if(s.complete)
{
s.complete(xml, status);
} ;
jQuery(io).unbind();
setTimeout(function()
{ try
{
jQuery(io).remove();
jQuery(form).remove();
} catch(e)
{
jQuery.handleError(s, xml, null, e);
}
}, 100);
xml = null;
};
}
// Timeout checker
if( s.timeout > 0 )
{
setTimeout(function(){
if( !requestDone )
{
// Check to see ifthe request is still happening
uploadCallback( "timeout" );
}
}, s.timeout);
}
try
{
var form = jQuery('#' + formId);
jQuery(form).attr('action', s.url);
jQuery(form).attr('method', 'POST');
jQuery(form).attr('target', frameId);
if(form.encoding)
{
form.encoding = 'multipart/form-data';
}
else
{
form.enctype = 'multipart/form-data';
}
jQuery(form).submit();
} catch(e)
{
jQuery.handleError(s, xml, null, e);
}
if(window.attachEvent){
document.getElementById(frameId).attachEvent('onload', uploadCallback);
}
else{
document.getElementById(frameId).addEventListener('load', uploadCallback, false);
}
return {abort: function () {}};
},
uploadHttpData: function( r, type ) {
var data = !type;
data = type == "xml" || data ? r.responseXML : r.responseText;
// ifthe type is "script", eval it in global context
if( type == "script" )
{
jQuery.globalEval( data );
}
// Get the JavaScript object, ifJSON is used.
if( type == "json" )
{
eval( "data = " + data );
}
// evaluate scripts within html
if( type == "html" )
{
jQuery("<div>").html(data).evalScripts();
}
return data;
}
});
upload.action------------------------------------------
package com.tjopen.define.action;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.tjopen.base.util.Util;
@SuppressWarnings("serial")
public class UploadAction extends ActionSupport {
private File zip;
private String zipFileName;
private String realpath;
private String filePath;
public void uploadphoto(){
HttpServletResponse response = ServletActionContext.getResponse();
response.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
// 保存到项目的路径下
String basePath = ServletActionContext.getServletContext().getRealPath("/");
SimpleDateFormat formater = new SimpleDateFormat("yyyy-M-dd");
String middlePath = "resources/photo/" + formater.format(new Date());
String tempMiddlePath = "";
// 生成时间戳文件夹路径
String str = "";
for (int i = 1; i < 100000; i++) {
tempMiddlePath = middlePath + "_" + i + "/";
str = middlePath + "_" + (i - 1 < 1 ? 1 : i - 1) + "/";
File parentDir = new File(basePath + tempMiddlePath);
if (parentDir.exists()) {
continue;
} else {
parentDir = new File(basePath + str);
if (parentDir != null && parentDir.list() != null && parentDir.list().length < 200) {
middlePath = str;
} else {
middlePath = tempMiddlePath;
}
break;
}
}
// 保存文件名
String filename=zipFileName;
String savefilePath=basePath+middlePath+filename;
File savefile = new File(savefilePath);
String result=middlePath+filename;
if(zip!= null){
try {
FileUtils.copyFile(zip, savefile);
} catch (IOException e) {
result="false";
}
}
else{
result="false";
}
try {
response.getWriter().print(result);
} catch (IOException e) {
e.printStackTrace();
}
}
public File getZip() {
return zip;
}
public void setZip(File zip) {
this.zip = zip;
}
public String getZipFileName() {
return zipFileName;
}
public void setZipFileName(String zipFileName) {
this.zipFileName = zipFileName;
}
public String getFilePath() {
return filePath;
}
public void setFilePath(String filePath) {
this.filePath = filePath;
}
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询