在jsp页面上怎么用Java语言实现图片上传

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了在jsp页面上怎么用Java语言实现图片上传相关的知识,希望对你有一定的参考价值。

---upload.jsp
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<%@ page contentType="text/html;charset=gb2312"%>
<html><title><%= application.getServerInfo() %></title>
<body>
上传文件
<form action="doUpload.jsp" method="post" enctype="multipart/form-data">
<%-- 类型enctype用multipart/form-data,
这样可以把文件中的数据作为流式数据上传,不管是什么文件类型,均可上传。--%>
请选择要上传的文件
<input type="file" name="upfile" size="50">
<input type="submit" value="提交">
</form></body>
</html>

----doUpload.jsp
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://"
+ request.getServerName() + ":" + request.getServerPort()
+ path + "/";
%>

<%@ page contentType="text/html; charset=GBK"%>
<%@ page import="java.io.*"%>
<%@ page import="java.util.*"%>
<%@ page import="javax.servlet.*"%>
<%@ page import="javax.servlet.http.*"%>
<html>
<head>
<title>upFile</title>
</head>
<body bgcolor="#ffffff">
<%
//定义上载文件的最大字节
int MAX_SIZE = 102400 * 102400;
//创建根路径的保存变量
String rootPath;
//声明文件读入类
DataInputStream in = null;
FileOutputStream fileOut = null;
//取得客户端的网络地址
String remoteAddr = request.getRemoteAddr();
//获得服务器的名字
String serverName = request.getServerName();
//取得互联网程序的绝对地址
String realPath = request.getRealPath(serverName);
realPath = realPath.substring(0, realPath.lastIndexOf("\\"));
//创建文件的保存目录
rootPath = realPath + "\\upload\\";
//取得客户端上传的数据类型
String contentType = request.getContentType();
try
if (contentType.indexOf("multipart/form-data") >= 0)
//读入上传的数据
in = new DataInputStream(request.getInputStream());
int formDataLength = request.getContentLength();
if (formDataLength > MAX_SIZE)
out.println("<P>上传的文件字节数不可以超过" + MAX_SIZE + "</p>");
return;

//保存上传文件的数据
byte dataBytes[] = new byte[formDataLength];
int byteRead = 0;
int totalBytesRead = 0;
//上传的数据保存在byte数组
while (totalBytesRead < formDataLength)
byteRead = in.read(dataBytes, totalBytesRead,
formDataLength);
totalBytesRead += byteRead;

//根据byte数组创建字符串
String file = new String(dataBytes);
//out.println(file);
//取得上传的数据的文件名
String saveFile = file.substring(file
.indexOf("filename=\"") + 10);
saveFile = saveFile.substring(0, saveFile.indexOf("\n"));
saveFile = saveFile.substring(
saveFile.lastIndexOf("\\") + 1, saveFile
.indexOf("\""));
int lastIndex = contentType.lastIndexOf("=");
//取得数据的分隔字符串
String boundary = contentType.substring(lastIndex + 1,
contentType.length());
//创建保存路径的文件名
String fileName = rootPath + saveFile;//out.print(fileName);
int pos;
pos = file.indexOf("filename=\"");
pos = file.indexOf("\n", pos) + 1;
pos = file.indexOf("\n", pos) + 1;
pos = file.indexOf("\n", pos) + 1;
int boundaryLocation = file.indexOf(boundary, pos) - 4;
//out.println(boundaryLocation);
//取得文件数据的开始的位置
int startPos = ((file.substring(0, pos)).getBytes()).length;
//out.println(startPos);
//取得文件数据的结束的位置
int endPos = ((file.substring(0, boundaryLocation))
.getBytes()).length;
//out.println(endPos);
//检查上载文件是否存在
File checkFile = new File(fileName);
if (checkFile.exists())
out.println("<p>" + saveFile + "文件已经存在.</p>");

//检查上载文件的目录是否存在
File fileDir = new File(rootPath);
if (!fileDir.exists())
fileDir.mkdirs();

//创建文件的写出类
fileOut = new FileOutputStream(fileName);
//保存文件的数据
fileOut.write(dataBytes, startPos, (endPos - startPos));
fileOut.close();
out.println(saveFile + "文件成功上载.</p>");
request.getSession().setAttribute("fileName",saveFile);
else
String content = request.getContentType();
out.println("<p>上传的数据类型不是multipart/form-data</p>");

catch (Exception ex)
throw new ServletException(ex.getMessage());

%>
</body>
</html>
参考技术A 下面是upload.jsp

<%@ page contentType="text/html; charset=gbk" language="java" import="java.sql.*" errorPage="" pageEncoding="gbk"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ page import="com.jspsmart.upload.*,com.eaio.uuid.UUID"%>
<%@ page import="org.vm.common.util.*"%>

<%!
String path="";
boolean isupload=false;
String cmd=null;
String fileName="";
%>
<%
cmd="";
isupload=false;
SmartUpload su=null;
String target=request.getParameter("target");//

String savePath="/soft/markets/000/upload/card/";
//FileUtils.createFolder(savePath);
try
su=new SmartUpload();
su.initialize(pageContext);
su.setAllowedFilesList("jpg,gif,jpeg,bmp,JPG,GIF,JPEG,BMP");
su.setDeniedFilesList("exe,bat,jsp,asp,aspx,php,htm,html,doc,txt");
//单个文件最大限制
su.setMaxFileSize(10240000);
su.upload();
cmd=su.getRequest().getParameter("cmd");
catch(Exception e)


if(cmd!=null&&cmd.equals("ok"))

//out.println("in upload");
//执行上传操作
com.jspsmart.upload.File file=su.getFiles().getFile(0);
if(file.isMissing())

out.println("文件上传失败!");
out.close();

else

//上传成功
//fileName = System.currentTimeMillis()+"-"+file.getFileName();
String ext=file.getFileExt();
fileName = new UUID().toString()+(ext!=null?"."+ext:"");
try
path=savePath+fileName;
file.saveAs(path,su.SAVE_VIRTUAL);
isupload=true;
catch(Exception e)
out.println("fail"+e.getMessage());
tryout.close();catch(Exception ex)



%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gbk" />
<%@ include file="../../../../../../check.jsp"%>
<%@ include file="../../../../../../public/js/script.jsp"%>
<link href="../../css/master.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript">
function chkForm()

var obj=document.all.form1;
if(obj.file.value=="")

alert("没有文件上传!");
return false;


return confirm("真的要上传吗?");


<% if(isupload) %>
alert("上传成功!");
cnmarket.closeDialog(filename:"<%=fileName%>");
<% %>
</script>
<title></title>
</head>
<body style="height:100px;">
<form action="" method="post" id="form1" name="form1" enctype="multipart/form-data" onSubmit="return chkForm();">
<table width="100%" height="100%" border="0" cellspacing="1" class="listTable">
<input type="hidden" name="cmd" value="ok">
<tr class="listOdd">
<td width="14%" height="20" align="right"><p align="right">上传文件:</p></td>
<td width="50%"><p align="left"><input name="file" id="file" type="file" /></p></td>
</tr>
<tr class="listDual">
<td colspan="2">
<input type="submit" class="dataBtn" value="上传"/> 
<input type="button" class="dataBtn" value="关闭" onclick="cnmarket.closeDialog(true)"/>
</td>
</tr>
</table>
</form>
</body>
</html>
其他页面调用这个页面。。。。

<script language="javascript">

upload = function()
cnmarket.uploadFile("fitment.enclosure",null,null,function(data)
if(data["filename"])
document.getElementById("fitment.enclosure").value=data["filename"];

);



</script>

<input name="fitment.enclosure" type="text" class="inpt2" readOnly value="<c:out value="$fitment.enclosure"/>">
<input type="button" class="dataBtn" value="上传" onclick="upload();"/>本回答被提问者和网友采纳
参考技术B 你可以先读取出流 打印出来看看 然后自己去解析那个流 是可以生成图片的 不过大多都用三方包

在jsp页面上用file控件添加一个本地图片的路径,然后在旁边的img中显示出来,并且不刷新页面

用ajax实现怎么办啊 求助大神!!!急急急!!!

把图片上传到服务器后,再把服务器上那个图片路径读出来返回到页面,然后把<img>的src属性替换成返回来的图片路径就可以了追问

不刷新页面 怎么上传啊

追答

用ajax把数据传回去再把图片路径返回来

追问

用js可以获得file控件的value么?怎么能获得到file中的value ?谢谢

追答

,在js中获取name的value,用ajax传到后台去

ajax部分建议用jQuery.post(url,name:value,function(data)//data就返回来的路径),一句话搞定,后台用out.print();传回来这个你知道的吧

参考技术A 现在我的情况是可以成功上传图片,并把其名称提交到数据库,可是图片却在本之后用IMG控制路径显示小图或者大图网上有等比例缩放图片的java类 我空间也有,pgYrkz

以上是关于在jsp页面上怎么用Java语言实现图片上传的主要内容,如果未能解决你的问题,请参考以下文章

在jsp页面上用file控件添加一个本地图片的路径,然后在旁边的img中显示出来,并且不刷新页面

java实现图片上传至服务器并显示,如何做?

在jsp和asp中怎么用FCkeditor上传图片和flash等到服务器啊?

java实现图片上传至服务器并显示,如何做?希望要具体的代码实现

jsp中怎样把图片显示在界面上?

C# 怎么实现上传图片到数据库 代码