当前位置:首页 » 文件管理 » jsp上传

jsp上传

发布时间: 2022-02-17 14:29:52

❶ jsp简单上传代码

servlet文件上传
login.jsp

<%@ page language="java" contentType="text/html; charset=gbk"
pageEncoding="gbk"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Insert title here</title>
</head>
<body>
<form action="upload" method="post" enctype="multipart/form-data">
输入用户名<input typ="text" name ="username">
<input type="file"name="file"/>
<input type="submit" value="submit"/>
</form>
</body>
</html>

result.jsp

<%@ page language="java" contentType="text/html; charset=gbk"
pageEncoding="gbk"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>上传结果页面</title>
</head>
<body>
username:${requestScope.username }
filename:${requestScope.file }
</body>
</html>

UploadServlet.java

package com.test.servlet;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

public class UploadServlet extends HttpServlet {

public UploadServlet() {

}

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String path = request.getSession().getServletContext().getRealPath("/upload");
DiskFileItemFactory factory = new DiskFileItemFactory();

factory.setRepository(new File(path));
factory.setSizeThreshold(1024 * 1024);

ServletFileUpload upload = new ServletFileUpload(factory);

try
{
List<FileItem>list = upload.parseRequest(request);
for(FileItem item:list){
if(item.isFormField()){
String name = item.getFieldName();
String value = item.getString("utf-8");
request.setAttribute(name, value);
}
else{
String name = item.getFieldName();
String value = item.getName();
int start = value.lastIndexOf("\\");
String fileName = value.substring(start+1);
request.setAttribute(name, fileName);
System.out.println(fileName);
OutputStream os = new FileOutputStream(new File(path,fileName));
InputStream is = item.getInputStream();

byte[] buffer = new byte[400];
int length = 0;
while((length = is.read(buffer))>0){
os.write(buffer,0,length);
}
os.close();
is.close();
}
}
}
catch(Exception e){
e.printStackTrace();
}

request.getRequestDispatcher("/result.jsp").forward(request, response);
}

}

Struts文件上传

1.创建一个工程:

创建一个JSP页面内容如下:

<body>

<form action="uploadAction.do" method="post" enctype="multipart/form-data" >

<input type="file" name="file">

<input type="submit">

</form>

</body>

2.创建一个FormBean继承ActionForm

其中有个private FormFile file ;属性。FormFile类的全名为:org.apache.struts.upload.FormFile

3.创建一个UploadAction继承自Action

然后重写Action的execute()方法:

代码如下:

public ActionForward execute(ActionMapping mapping, ActionForm form,

HttpServletRequest request, HttpServletResponse response) {

UploadForm uploadForm = (UploadForm) form;

if(uploadForm.getFile()!=null)

FileUtil.uploadFile(uploadForm.getFile(), "e:/abc/accp");

return null;

}

4.创建FileUtil工具类,里面实现上传的文件的方法:

关键代码如下:

public class FileUtil

{

/*** 创建空白文件

* @param fileName 文件名

* @param dir 保存文件的目录

* @return

*/

private static File createNewFile(String fileName,String dir)

{

File dirs = new File(dir);

//看文件夹是否存在,如果不存在新建目录

if(!dirs.exists())

dirs.mkdirs();

//拼凑文件完成路径

File file = new File(dir+File.separator+fileName);

try {

//判断是否有同名名字,如果有同名文件加随机数改变文件名

while(file.exists()){

int ran = getRandomNumber();

String prefix = getFileNamePrefix( fileName);

String suffix = getFileNameSuffix( fileName);

String name = prefix+ran+"."+suffix;

file = new File(dir+File.separator+name);

}

file.createNewFile();

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

return file;

}

/**

* 获得随机数

* @return

*/

private static int getRandomNumber() {

Random random = new Random(new Date().getTime());

return Math.abs(random.nextInt());

}

/**

* 分割文件名 如a.txt 返回 a

* @param fileName

* @return

*/

private static String getFileNamePrefix(String fileName){

int dot = fileName.lastIndexOf(".");

return fileName.substring(0,dot);

}

/**

* 获得文件后缀

* @param fileName

* @return

*/

private static String getFileNameSuffix(String fileName) {

int dot = fileName.lastIndexOf(".");

return fileName.substring(dot+1);

}

/**

* 上传文件

* @param file

* @param dir

* @return

*/

public static String uploadFile(FormFile file,String dir)

{

//获得文件名

String fileName = file.getFileName();

InputStream in = null;

OutputStream out = null;

try

{

in = new BufferedInputStream(file.getInputStream());//构造输入流

File f = createNewFile(fileName,dir);

out = new BufferedOutputStream(new FileOutputStream(f));//构造文件输出流

byte[] buffered = new byte[8192];//读入缓存

int size =0;//一次读到的真实大小

while((size=in.read(buffered,0,8192))!=-1)

{

out.write(buffered,0,size);

}

out.flush();

} catch (FileNotFoundException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

}

finally

{

try {

if(in != null) in.close();

} catch (IOException e) {

e.printStackTrace();

}

try {

if(out != null) out.close();

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

return null;

}

}

❷ 怎么在 jsp 页面中上传文件

使用jsp smartupload
示例:部分文件代码 具体实现 找些教材

UploadServlet.java

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.jspsmart.upload.*;
import java.text.*;
import java.util.*;

/*******************************************************/
/* 该实例中尽可能多地用到了一些方法,在实际应用中 */
/* 我们可以根据自己的需要进行取舍! */
/*******************************************************/

public class UploadServlet extends HttpServlet {

public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

// 新建一个SmartUpload对象,此项是必须的
SmartUpload myupload = new SmartUpload();
// 初始化,此项是必须的
ServletConfig config = getServletConfig();
myupload.initialize(config,request,response);

response.setContentType("text/html");
response.setCharacterEncoding("gb2312");
PrintWriter out = response.getWriter();
out.println("<h2>处理上传的文件</h2>");
out.println("<hr>");

try{
// 限制每个上传文件的最大长度
myupload.setMaxFileSize(1024*1024);
// 限制总上传数据的长度
myupload.setTotalMaxFileSize(5*1024*1024);
// 设定允许上传的文件(通过扩展名限制)
myupload.setAllowedFilesList("doc,txt,jpg,gif");
// 设定禁止上传的文件(通过扩展名限制)
myupload.setDeniedFilesList("exe,bat,jsp,htm,html,,");
// 上传文件,此项是必须的
myupload.upload();
// 统计上传文件的总数
int count = myupload.getFiles().getCount();
// 取得Request对象
Request myRequest = myupload.getRequest();
String rndFilename,fileExtName,fileName,filePathName,memo;
Date dt = null;
SimpleDateFormat fmt = new SimpleDateFormat("yyyyMMddHHmmssSSS");

// 逐一提取上传文件信息,同时可保存文件
for (int i=0;i<count;i++)
{
//取得一个上传文件
File file = myupload.getFiles().getFile(i);
// 若文件不存在则继续
if (file.isMissing()) continue;
// 取得文件名
fileName = file.getFileName();
// 取得文件全名
filePathName = file.getFilePathName();
// 取得文件扩展名
fileExtName = file.getFileExt();
// 取得随机文件名
dt = new Date(System.currentTimeMillis());
Thread.sleep(100);
rndFilename= fmt.format(dt)+"."+fileExtName;
memo = myRequest.getParameter("memo"+i);

// 显示当前文件信息
out.println("第"+(i+1)+"个文件的文件信息:<br>");
out.println(" 文件名为:"+fileName+"<br>");
out.println(" 文件扩展名为:"+fileExtName+"<br>");
out.println(" 文件全名为:"+filePathName+"<br>");
out.println(" 文件大小为:"+file.getSize()+"字节<br>");
out.println(" 文件备注为:"+memo+"<br>");
out.println(" 文件随机文件名为:"+rndFilename+"<br><br>");

// 将文件另存,以WEB应用的根目录作为上传文件的根目录
file.saveAs("/upload/" + rndFilename,myupload.SAVE_VIRTUAL);
}
out.println(count+"个文件上传成功!<br>");
}catch(Exception ex){
out.println("上传文件超过了限制条件,上传失败!<br>");
out.println("错误原因:<br>"+ex.toString());
}
out.flush();
out.close();
}

}

❸ jsp文件上传

public class MultipartTestServlet extends HttpServlet {

public MultipartTestServlet() { //构造方法

super();

}

public void doPost(HttpServletRequest request, HttpServletResponse response) //servlet的doPost方法处理POST请求

throws ServletException, IOException { //抛出异常

request.setCharacterEncoding("gbk"); //设置字符为GBK

RequestContext requestContext = new ServletRequestContext(request); //实例化RequestContext对象

if(FileUpload.isMultipartContent(requestContext)){
//判断是否包含 multipart 内容

DiskFileItemFactory factory = new DiskFileItemFactory();
// 创建基于磁盘的文件工厂
factory.setRepository(new File("c:/tmp/")); // 设置临时目录

ServletFileUpload upload = new ServletFileUpload(factory);

upload.setHeaderEncoding("gbk");

upload.setSizeMax(2000000); //设置缓冲区大小

List items = new ArrayList();

try {

items = upload.parseRequest(request); // 得到所有的文件

} catch (FileUploadException e1) {

System.out.println("文件上传发生错误" + e1.getMessage());

}

Iterator it = items.iterator();

while(it.hasNext()){

FileItem fileItem = (FileItem) it.next();

if(fileItem.isFormField()){

System.out.println(fileItem.getFieldName() + " " + fileItem.getName() + " " + new String(fileItem.getString().getBytes("iso8859-1"), "gbk")); //获得表单中域的名字。获得从浏览器中取得的文件全路径

}else{

System.out.println(fileItem.getFieldName() + " " +

fileItem.getName() + " " +

fileItem.isInMemory() + " " +

fileItem.getContentType() + " " +

fileItem.getSize());

if(fileItem.getName()!=null && fileItem.getSize()!=0){
// 浏览器中取得的文件全路径不为空 大小 不为0 则写入

File fullFile = new File(fileItem.getName());

File newFile = new File("c:/temp/" + fullFile.getName());

try {

fileItem.write(newFile);

} catch (Exception e) {

e.printStackTrace();

}

}else{

System.out.println("文件没有选择 或 文件内容为空");

}

}

}

}

}

}

❹ jsp如何上传文件

只是jsp部分的话,只要在form标签里加一个“enctype="multipart/form-data"”就好了,读取下载的话只要弄个commons-fileupload之类的插件就很容易解决
这里是下载部分的核心代码:
<%@ page contentType="text/html;charset=gb2312" import="com.jspsmart.upload.*" %>
<%
String sUrl = (String)request.getAttribute("fileurl");
SmartUpload su = new SmartUpload();
su.initialize(pageContext);
//设定contentDisposition为null以禁止浏览器自动打开文件,保证点击链接后是下载文件。若不设定,则下载的文件扩展名为doc时,浏览器将自动用word打开它;扩展名为pdf时,浏览器将用acrobat打开。
su.setContentDisposition(null);
su.downloadFile(sUrl);
%>
但是归根结底,你还是要一个存放文件路径的数据库啊,否则你下载时候下载地址每次都写死或者手动输入??如果要动态读取的话还是要建一个存放文件路径的数据库的

❺ jsp怎么上传文件

上传文件程序应用示例
<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 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>");
}else{
String content = request.getContentType();
out.println("<p>上传的数据类型不是multipart/form-data</p>");
}
}catch(Exception ex){
throw new ServletException(ex.getMessage());
}
%>
</body>
</html>

❻ jsp页面中如何视频文件上传的代码实现

jsp 获取视频文件进行播放 跟html没什么区别 可以调用不同播放器的代码 ,比如MEDIA播放器:
<OBJECT ID="mediaplayer" WIDTH="50%" HEIGHT="50%" CLASSID="CLSID:6BF52A52-394A-11d3-B153-00C04F79FAA6">
<!--播放的文件的地址-->
<param name="url" value="http://www..com"/>
<!--去除右键菜单-->
<param name="enableContextMenu" value="false"/>
<param name="autoStart" value="true" />
</OBJECT>

❼ JSP如何上传图片

jsp使用I/O文件操作类,可以将图片转成二进制的形式,然后保存在服务器中的一个文件夹,示例如下:

<%...@pagecontentType="text/html;charset=gb2312"%>
<%...@pageimport="java.util.*"%>
<%...@pageimport="java.text.*"%>
<%...@pageimport="java.io.*"%>
<%...@pageimport="com.sun.image.codec.jpeg.*"%>
<%...@pageimport="java.awt.image.*"%>
<%...@pageimport="java.awt.*"%>

<%...
Stringname=request.getParameter("name");
name=newString(name.getBytes("ISO-8859-1"));
Stringima=request.getParameter("image");

try{
Stringpath=request.getRealPath("/");
FileOutputStreamot=newFileOutputStream(path+name+".jpg");
//ServletOutputStreamot=response.getOutputStream();//也可以直接输出显示
FileInputStreamin=newFileInputStream(ima);
JPEGImageDecoderjpgCodec=JPEGCodec.createJPEGDecoder(in);
BufferedImageimage=jpgCodec.decodeAsBufferedImage();
JPEGImageEncoderencoder=JPEGCodec.createJPEGEncoder(ot);
encoder.encode(image);
in.close();
ot.close();
out.print("JSP上传图片成功!<BR>");
//加载上传成功的图片
out.print("<IMGwidth=200height=200src='"+name+".jpg'/>");
}
catch(Exceptione)
{
System.out.print(e.toString());
}
%>

❽ Java jsp页面的上传按钮

<input type="file" name="uploadify" id="file_upload" />

❾ 用jsp 怎样实现文件上传

你下载一个jspsmart组件,网上很容易下到,用法如下,这是我程序的相关片断,供你参考: <%@ page import="com.jspsmart.upload.*" %>
<jsp:useBean id="mySmartUpload" scope="page" class="com.jspsmart.upload.SmartUpload" />
<%
String photoname="photoname";

// Variables
int count=0; // Initialization
mySmartUpload.initialize(pageContext); // Upload
mySmartUpload.upload();

for (int i=0;i<mySmartUpload.getFiles().getCount();i++){ // Retreive the current file
com.jspsmart.upload.File myFile = mySmartUpload.getFiles().getFile(i); // Save it only if this file exists
if (!myFile.isMissing()) {
java.util.Date thedate=new java.util.Date();
java.text.DateFormat df = new java.text.SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
photoname = df.format(thedate);
photoname +="."+ myFile.getFileExt();
myFile.saveAs("/docs/docimg/" + photoname);
count ++; } }
%>
<% String title="1";
String author="1";
String content="1";
String pdatetime="1";
String topic="1";
String imgintro="1";
String clkcount="1"; if(mySmartUpload.getRequest().getParameter("title")!=null){
title=(String)mySmartUpload.getRequest().getParameter("title");
title=new String(title.getBytes("gbk"),"ISO-8859-1");
}
if(mySmartUpload.getRequest().getParameter("author")!=null){
author=(String)mySmartUpload.getRequest().getParameter("author");
author=new String(author.getBytes("gbk"),"ISO-8859-1");
}
if(mySmartUpload.getRequest().getParameter("content")!=null){
content=(String)mySmartUpload.getRequest().getParameter("content");
content=new String(content.getBytes("gbk"),"ISO-8859-1");
}
if(mySmartUpload.getRequest().getParameter("pdatetime")!=null){
pdatetime=(String)mySmartUpload.getRequest().getParameter("pdatetime");
}
if(mySmartUpload.getRequest().getParameter("topic")!=null){
topic=(String)mySmartUpload.getRequest().getParameter("topic");
}
if(mySmartUpload.getRequest().getParameter("imgintro")!=null){
imgintro=(String)mySmartUpload.getRequest().getParameter("imgintro");
imgintro=new String(imgintro.getBytes("gbk"),"ISO-8859-1");
}
if(mySmartUpload.getRequest().getParameter("clkcount")!=null){
clkcount=(String)mySmartUpload.getRequest().getParameter("clkcount");
}
//out.println(code+name+birthday);
%>

❿ jsp上传图片,最好完整代码。100分!

upfile.jsp 文件代码如下:

<form method="post" action="uploadimage.jsp" name="form1" enctype="multipart/form-data">
<input type="file" name="file">
<input type="submIT" name="sub" value="upload">
</form>
<form method="post" action="uploadimage.jsp" name="form1" enctype="multipart/form-data">
<input type="file" name="file">
<input type="submit" name="sub" value="upload">
</form>
<STRONG><FONT color=#ff0000>uploadimage.jsp</FONT></STRONG>
文件代码如下:
uploadimage.jsp
文件代码如下:view plain to clipboardprint?
<PRE class=java name="code"><%@ page language="java" pageEncoding="gb2312"%>
<%@ page import="java.io.*,java.awt.Image,java.awt.image.*,com.sun.image.codec.jpeg.*,java.sql.*,com.jspsmart.upload.*,java.util.*"%>
<%@ page import="mainClass.*" %>
<html>
<head>
<title>My JSP 'uploadimage.jsp' starting page</title>
</head>
<body>
<%
SmartUpload sma=new SmartUpload();
long file_max_size=4000000;
String filename1="",ext="",testvar="";
String url="uploadfiles/";
sma.initialize(pageContext);
try
{
sma.setAllowedFilesList("jpg,gif");
sma.upload();
}catch(Exception e){
%>
<script language="jscript">
alert("只允许上传jpg,gif图片")
window.location.href="upfile.jsp"
</script>
<%
}
try{
com.jspsmart.upload.File myf=sma.getFiles().getFile(0);
if(myf.isMissing()){
%>
<script language="jscript">
alert("请选择要上传的文件!")
window.location.href="upfile.jsp"
</script>
<%
}else{
ext=myf.getFileExt();
int file_size=myf.getSize();
String saveurl="";
if(file_size < file_max_size){
Calendar cal=Calendar.getInstance();
String filename=String.valueOf(cal.getTimeInMillis());
saveurl=request.getRealPath("/")+url;
saveurl+=filename+"."+ext;
myf.saveAs(saveurl,sma.SAVE_PHYSICAL);
myclass mc=new myclass(request.getRealPath("data/data.mdb"));
mc.executeInsert("insert into [path] values('uploadfiles/"+filename+"."+ext+"')");
out.println("图片上传成功!");
response.sendRedirect("showimg.jsp");
}
}
}catch(Exception e){
e.printStackTrace();
}
%>
</body>
</html>
</PRE>

本文来自: IT知道网(http://www.itwis.com) 详细出处参考:http://www.itwis.com/html/java/jsp/20080916/2409.html

热点内容
php平滑重启 发布:2024-10-26 12:25:33 浏览:945
竹压缩板材 发布:2024-10-26 12:21:32 浏览:754
重大校园网服务器地址 发布:2024-10-26 12:06:10 浏览:876
js引入php 发布:2024-10-26 12:05:48 浏览:469
编程扩大条件 发布:2024-10-26 11:58:06 浏览:341
pcb编译设置 发布:2024-10-26 11:53:49 浏览:595
ftp命令上传 发布:2024-10-26 11:48:10 浏览:934
vue怎么上传微信 发布:2024-10-26 11:35:13 浏览:556
vba算法 发布:2024-10-26 11:33:44 浏览:64
javarsa加密 发布:2024-10-26 11:33:25 浏览:250