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

上传文件jsp

发布时间: 2022-07-29 16:32:09

① 怎么在 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上传文件的问题

用JSP实现文件上传功能,参考如下:
UploadExample.jsp

<%@ 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 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文件放在同一路径下,运行UploadExample.jsp即可。

③ JSP中 上传文件的问题

tank_upresult.jsp文件内容

<%@ page import="tk1.tank_file" %>
<%@ page contentType="text/html; charset=gb2312" %>
<html>
<body bgcolor=cyan>
<font size=5>
<p>请选择要上传的目录名:
<form action="info.jsp" method="post" name="form1" >
<select name="afileitem"> <!-- 选择目录 -->
<option value="c:\vlan"> vlan
<option value="c:\eve">eve
<option value="c:\feng">feng
</select>
输入将上传文件的名字:<input type="text" name="newfilename"> <!--要上传的文件名字 -->
<p>输入文件内容:
<p><textarea name="newfilecontent" rows="20" cols="60"></textarea> <!--上传的内容 -->
<input type="submit" value="dataup" name="up">
</form>
</font>
</body>
</html>

下面是调用的BEAN中的写操作的片段:

package tk1;
import java.io.*;
public class tank_file {
String newfilename,afileitem;
String newfilecontent,upmessage;
String result;
public void setAfileitem(String a){ //存放文件的地址
afileitem=a;
}
public void setNewfilename(String d){ //存放目录的名字
newfilename=d;
}
public String getNewfilename(){
return newfilename;
}
public void setNewfilecontent(String c){ //写入JSP中上传的内容
newfilecontent=c;

}
public void writefile(){
File dr=new File(afileitem);
if ( ! (dr.exists() && dr.isDirectory())){
dr.mkdir();
}
byte temp2[]=newfilecontent.getBytes();
try{
File content=new File(afileitem,newfilename);
FileOutputStream out=new FileOutputStream(content);
out.write(temp2,0,temp2.length);
out.close();
upmessage="success upload file :"+afileitem+"\\"+newfilename; //返回成功信息,并显示存放目录。
}
catch(Exception e){
upmessage="fail"; //返回失败信息
e.printStackTrace();
}

}
public String getUpmessage(){
return upmessage;
}
}

接收反馈信息的界面info.jsp
<%@ page import="tk1.tank_file" %>
<%@ page contentType="text/html; charset=gb2312"%>
<jsp:useBean id="up" class="tk1.tank_file" scope="page">
<jsp:setProperty name="up" property="*"/>
</jsp:useBean>

<html><body bgcolor=cyan><font size=2>
<%
up.writefile();
out.println(up.getUpmessage());
%>
</font>
</body>

④ jsp如何实现文件上传与下载

如果服务器端程序使用的是struts2框架的话,我会,其他的不会。
struts2:
对于上传,jsp页面只需要有个file类型的表单域,如<input type="file" name="xxx" />
struts2的接收请求的action中再写三个属性与这个表单域的名称对应起来,他们是,File类型的xxx,String类型的xxxFileName,String类型的xxxContentType,并其设置相应的set/get方法。则框架负责接收上传文件的字节流,解析文件名,文件类型,直接使用即可。
对于下载,只需要在action的配置文件中设置如下返回值类型和相应参数:
<result type="stream">
<param name="contentType">application/octet-stream</param>
<param name="inputName">inputStream</param>
<param name="contentDisposition">attachment;filename=xxx </param> xxx为下载文件的文件名
</result>
且在action总写一个返回值类型为InputStream的getInputStream方法,此方法返回你要下载的文件的流即可。
ps:其中contentDisposition的配置信息中attachment代表点击下载时浏览器先弹出个保存位置的提示框,然后再决定是否下载,默认是inline,即直接打开文件。

⑤ JSP上传文件

ServletFileUpload sfu = new ServletFileUpload(itemFactory);
// 设置上传文件的最大文件为10M
sfu.setSizeMax(0xA00000);
限制上传文件的的最大值的属性值设置

⑥ 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 如何实现文件上传和下载功能

1.jsp页面
<s:form action="fileAction" namespace="/file" method="POST" enctype="multipart/form-data">
<!-- name为后台对应的参数名称 -->
<s:file name="files" label="file1"></s:file>
<s:file name="files" label="file2"></s:file>
<s:file name="files" label="file3"></s:file>
<s:submit value="提交" id="submitBut"></s:submit>
</s:form>
2.Action
//单个文件上传可以用 File files,String filesFileName,String filesContentType
//名称要与jsp中的name相同(三个变量都要生成get,set)
private File[] files;
// 要以File[]变量名开头
private String[] filesFileName;
// 要以File[]变量名开头
private String[] filesContentType;

private ServletContext servletContext;

//Action调用的上传文件方法
public String execute() {
ServletContext servletContext = ServletActionContext.getServletContext();
String dataDir = servletContext.getRealPath("/file/upload");
System.out.println(dataDir);
for (int i = 0; i < files.length; i++) {
File saveFile = new File(dataDir, filesFileName[i]);
files[i].renameTo(saveFile);
}
return "success";
}
3.配置上传文件临时文件夹(在struts.xml中配置)
<constant name="struts.multipart.saveDir" value="c:/temp"/>
文件下载
1.下载的url(到Action)
<a href="${pageContext.request.contextPath}/file/fileAction!down.action">下载</a>
2.struts.xml配置
<package name="file" namespace="/file" extends="struts-default">
<action name="fileAction" class="com.struts2.file.FileAction">
<!-- 下载文件配置 -->
<!--type 为 stream 应用 StreamResult 处理-->
<result name="down" type="stream">
<!--
不管实际类型,待下载文件 ContentType 统一指定为 application/octet-stream
默认为 text/plain
-->
<param name="contentType">application/octet-stream</param>
<!--
默认就是 inputStream,它将会指示 StreamResult 通过 inputName 属性值的 getter 方法,
比如这里就是 getInputStream() 来获取下载文件的内容,意味着你的 Action 要有这个方法
-->
<param name="inputName">inputStream</param>
<!--
默认为 inline(在线打开),设置为 attachment 将会告诉浏览器下载该文件,filename 指定下载文
件保有存时的文件名,若未指定将会是以浏览的页面名作为文件名,如以 download.action 作为文件名,
这里使用的是动态文件名,${fileName}, 它将通过 Action 的 getFileName() 获得文件名
-->
<param name="contentDisposition">attachment;filename="${fileName}"</param>
<!-- 输出时缓冲区的大小 -->
<param name="bufferSize">4096</param>
</result>
</action>
</package>
3.Action
//Action调用的下载文件方法
public String down() {
return "down";
}

//获得下载文件的内容,可以直接读入一个物理文件或从数据库中获取内容
public InputStream getInputStream() throws Exception {
String dir = servletContext.getRealPath("/file/upload");
File file = new File(dir, "icon.png");
if (file.exists()) {
//下载文件
return new FileInputStream(file);

//和 Servlet 中不一样,这里我们不需对输出的中文转码为 ISO8859-1
//将内容(Struts2 文件下载测试)直接写入文件,下载的文件名必须是文本(txt)类型
//return new ByteArrayInputStream("Struts2 文件下载测试".getBytes());
}
return null;
}

// 对于配置中的 ${fileName}, 获得下载保存时的文件名
public String getFileName() {
String fileName ="图标.png";
try {
// 中文文件名也是需要转码为 ISO8859-1,否则乱码
return new String(fileName.getBytes(), "ISO8859-1");
} catch (UnsupportedEncodingException e) {
return "icon.png";
}
}

⑧ 用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中如何增加上传文件的功能

首先下载jspsmartupload组件 这个你自己找吧,现在发链接太难了。
二、将目录jspsmartupload/wib_inf/classes中的内容拷贝到网站所在的实际目录中的WEB-INF中(resin是这个目录,其他的可能是classes,具体请查阅jspsmartupload/help/setup.htm)

三、假如是resin运行JSP,请在resin的conf/resin.conf中的
<web-app> 和 </web-app> 中加入:
<path-mapping url-pattern=’/upload/*’ real-path=’f:\\jsp\\jspsmartupload\\upload’/>

四、上传界面的代码如下:(文件名:insert.htm)
<FORM METHOD="POST" ACTION=" uploadfile.jsp" ENCTYPE="multipart/form-data">
<INPUT TYPE="FILE" NAME="FILE1" SIZE="50"> <BR>
<INPUT TYPE="FILE" NAME="FILE2" SIZE="50"> <BR>
<INPUT TYPE="FILE" NAME="FILE3" SIZE="50"> <BR>
<INPUT TYPE="FILE" NAME="FILE4" SIZE="50"> <BR>
主题: <input type="text" name="text1" > <br>
<INPUT type=submit value=写 完 name=ok>
</form>
注重上面的real-path目录

五、uploadfile.jsp的代码如下:
<%@page contentType="text/html;charset=gb2312"
language="java"
import="com.jspsmart.upload.*"%>
<jsp:useBean id="mySmartUpload"
scope="page"
class="com.jspsmart.upload.SmartUpload" />

⑩ 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>

热点内容
英雄联盟技能脚本 发布:2024-05-17 14:59:41 浏览:444
全名k歌安卓手机里面怎么录屏 发布:2024-05-17 14:40:07 浏览:180
常用数据库介绍 发布:2024-05-17 14:31:38 浏览:504
中孚存储介质信息消除工具 发布:2024-05-17 14:31:33 浏览:589
服务器访问ip如何调转主页 发布:2024-05-17 14:30:33 浏览:789
好玩的解压化妆小游戏 发布:2024-05-17 14:10:57 浏览:127
交通银行怎么登陆不了密码 发布:2024-05-17 13:54:48 浏览:543
安卓如何自动连接无线 发布:2024-05-17 13:53:51 浏览:262
python的urlparse 发布:2024-05-17 13:44:20 浏览:769
linux命令全称 发布:2024-05-17 12:07:54 浏览:110