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

jsp文件上传和下载

发布时间: 2024-05-09 07:09:16

① 怎么在 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怎么下载上传文件

去apache网站上下个common-fileupload上传组件用就可以了!

③ JSP做的简单的文件上传下载代码

//////////////////////用Servlvet实现文件上传,参考参考吧
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class UploadTest extends HttpServlet {
String rootPath, successMessage;

static final int MAX_SIZE = 102400;
public void init(ServletConfig config) throws ServletException
{
super.init(config);
}

public void doGet(HttpServletRequest request,HttpServletResponse response)
throws ServletException,IOException
{
response.setContentType("text/html");
PrintWriter out = new PrintWriter (response.getOutputStream());
out.println("<html>");
out.println("<head><title>Servlet1</title></head>");
out.println("<body><form ENCTYPE=\"multipart/form-data\" method=post action=''><input type=file enctype=\"multipart/form-data\" name=filedata>");
out.println("<input type=submit></form>");
out.println("</body></html>");
out.close();
}

public void doPost(HttpServletRequest request,HttpServletResponse response)
{
ServletOutputStream out=null;
DataInputStream in=null;
FileOutputStream fileOut=null;
try
{
/*set content type of response and get handle to output stream in case we are unable to redirect client*/
response.setContentType("text/plain");
out = response.getOutputStream();
}
catch (IOException e)
{
//print error message to standard out
System.out.println("Error getting output stream.");
System.out.println("Error description: " + e);
return;
}

try
{
String contentType = request.getContentType();
//make sure content type is multipart/form-data
if(contentType != null && contentType.indexOf("multipart/form-data") != -1)
{
//open input stream from client to capture upload file
in = new DataInputStream(request.getInputStream());
//get length of content data
int formDataLength = request.getContentLength();
//allocate a byte array to store content data
byte dataBytes[] = new byte[formDataLength];
//read file into byte array
int bytesRead = 0;
int totalBytesRead = 0;
int sizeCheck = 0;
while (totalBytesRead < formDataLength)
{
//check for maximum file size violation
sizeCheck = totalBytesRead + in.available();
if (sizeCheck > MAX_SIZE)
{
out.println("Sorry, file is too large to upload.");
return;
}
bytesRead = in.read(dataBytes, totalBytesRead, formDataLength);
totalBytesRead += bytesRead;
}
//create string from byte array for easy manipulation
String file = new String(dataBytes);
//since byte array is stored in string, release memory
dataBytes = null;
/*get boundary value (boundary is a unique string that
separates content data)*/
int lastIndex = contentType.lastIndexOf("=");
String boundary = contentType.substring(lastIndex+1,
contentType.length());
//get Directory web variable from request
String directory="";
if (file.indexOf("name=\"Directory\"") > 0)
{
directory = file.substring(file.indexOf("name=\"Directory\""));
//remove carriage return
directory = directory.substring(directory.indexOf("\n")+1);
//remove carriage return
directory = directory.substring(directory.indexOf("\n")+1);
//get Directory
directory = directory.substring(0,directory.indexOf("\n")-1);
/*make sure user didn't select a directory higher in the directory tree*/
if (directory.indexOf("..") > 0)
{
out.println("Security Error: You can't upload " +"to a directory higher in the directory tree.");
return;
}
}
//get SuccessPage web variable from request
String successPage="";
if (file.indexOf("name=\"SuccessPage\"") > 0)
{
successPage = file.substring(file.indexOf("name=\"SuccessPage\""));
//remove carriage return
successPage = successPage.substring(successPage.indexOf("\n")+1);
//remove carriage return
successPage = successPage.substring(successPage.indexOf("\n")+1);
//get success page
successPage = successPage.substring(0,successPage.indexOf("\n")-1);}
//get OverWrite flag web variable from request
String overWrite;
if (file.indexOf("name=\"OverWrite\"") > 0)
{
overWrite = file.substring(file.indexOf("name=\"OverWrite\""));
//remove carriage return
overWrite = overWrite.substring(
overWrite.indexOf("\n")+1);
//remove carriage return
overWrite = overWrite.substring(overWrite.indexOf("\n")+1);
overWrite = overWrite.substring(0,overWrite.indexOf("\n")-1);
}
else
{
overWrite = "false";
}
//get OverWritePage web variable from request
String overWritePage="";
if (file.indexOf("name=\"OverWritePage\"") > 0)
{
overWritePage = file.substring(file.indexOf("name=\"OverWritePage\""));
//remove carriage return
overWritePage = overWritePage.substring(overWritePage.indexOf("\n")+1);
//remove carriage return
overWritePage = overWritePage.substring(overWritePage.indexOf("\n")+1);
//get overwrite page
overWritePage = overWritePage.substring(0,overWritePage.indexOf("\n")-1);
}
//get filename of upload file
String saveFile = file.substring(file.indexOf("filename=\"")+10);
saveFile = saveFile.substring(0,saveFile.indexOf("\n"));
saveFile = saveFile.substring(saveFile.lastIndexOf("\\")+1,
saveFile.indexOf("\""));
/*remove boundary markers and other multipart/form-data
tags from beginning of upload file section*/
int pos; //position in upload file
//find position of upload file section of request
pos = file.indexOf("filename=\"");
//find position of content-disposition line
pos = file.indexOf("\n",pos)+1;
//find position of content-type line
pos = file.indexOf("\n",pos)+1;
//find position of blank line
pos = file.indexOf("\n",pos)+1;
/*find the location of the next boundary marker
(marking the end of the upload file data)*/
int boundaryLocation = file.indexOf(boundary,pos)-4;
//upload file lies between pos and boundaryLocation
file = file.substring(pos,boundaryLocation);
//build the full path of the upload file
String fileName = new String(rootPath + directory +
saveFile);
//create File object to check for existence of file
File checkFile = new File(fileName);
if (checkFile.exists())
{
/*file exists, if OverWrite flag is off, give
message and abort*/
if (!overWrite.toLowerCase().equals("true"))
{
if (overWritePage.equals(""))
{
/*OverWrite HTML page URL not received, respond
with generic message*/
out.println("Sorry, file already exists.");
}
else
{
//redirect client to OverWrite HTML page
response.sendRedirect(overWritePage);
}
return;
}
}
/*create File object to check for existence of
Directory*/
File fileDir = new File(rootPath + directory);
if (!fileDir.exists())
{
//Directory doesn't exist, create it
fileDir.mkdirs();
}
//instantiate file output stream
fileOut = new FileOutputStream(fileName);
//write the string to the file as a byte array
fileOut.write(file.getBytes(),0,file.length());
if (successPage.equals(""))
{
/*success HTML page URL not received, respond with
eneric success message*/
out.println(successMessage);
out.println("File written to: " + fileName);
}
else
{
//redirect client to success HTML page
response.sendRedirect(successPage);
}
}
else //request is not multipart/form-data
{
//send error message to client
out.println("Request not multipart/form-data.");
}
}
catch(Exception e)
{
try
{
//print error message to standard out
System.out.println("Error in doPost: " + e);
//send error message to client
out.println("An unexpected error has occurred.");
out.println("Error description: " + e);
}
catch (Exception f) {}
}
finally
{
try
{
fileOut.close(); //close file output stream
}
catch (Exception f) {}
try
{
in.close(); //close input stream from client
}
catch (Exception f) {}
try
{
out.close(); //close output stream to client
}
catch (Exception f) {}
}
}

}

④ jsp+servlet实现文件上传与下载源码

上传:
需要导入两个包:commons-fileupload-1.2.1.jar,commons-io-1.4.jar
import java.io.File;
import java.io.IOException;
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;

/**
* 上传附件
* @author new
*
*/
public class UploadAnnexServlet extends HttpServlet {

private static String path = "";

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

doPost(request, response);
}

/*
* post处理
* (non-Javadoc)
* @see javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

path = this.getServletContext().getRealPath("/upload");

try {
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload up = new ServletFileUpload(factory);
List<FileItem> ls = up.parseRequest(request);

for (FileItem fileItem : ls) {
if (fileItem.isFormField()) {
String FieldName = fileItem.getFieldName();
//getName()返回的是文件名字 普通域没有文件 返回NULL
// String Name = fileItem.getName();
String Content = fileItem.getString("gbk");
request.setAttribute(FieldName, Content);
} else {

String nm = fileItem.getName().substring(
fileItem.getName().lastIndexOf("\\") + 1);
File mkr = new File(path, nm);
if (mkr.createNewFile()) {
fileItem.write(mkr);//非常方便的方法
}
request.setAttribute("result", "上传文件成功!");
}
}
} catch (Exception e) {
e.printStackTrace();
request.setAttribute("result", "上传失败,请查找原因,重新再试!");
}
request.getRequestDispatcher("/pages/admin/annex-manager.jsp").forward(
request, response);
}

}

下载(i/o流)无需导包:
import java.io.IOException;
import java.net.URLEncoder;

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

/**
* 下载文件
* @author
*
*/
public class DownloadFilesServlet extends HttpServlet {

/**
*
*/
private static final long serialVersionUID = 8594448765428224944L;

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

doPost(request, response);
}

/*
* 处理请求
* (non-Javadoc)
* @see javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

String name = request.getParameter("fileName");

System.out.print("dddddddddd:" + name);
// web绝对路径
String path = request.getSession().getServletContext().getRealPath("/");
String savePath = path + "upload";

// 设置为下载application/x-download
response.setContentType("application/x-download");
// 即将下载的文件在服务器上的绝对路径
String filenamedownload = savePath + "/" + name;
// 下载文件时显示的文件保存名称
String filenamedisplay = name;
// 中文编码转换
filenamedisplay = URLEncoder.encode(filenamedisplay, "UTF-8");
response.addHeader("Content-Disposition", "attachment;filename="
+ filenamedisplay);
try {
java.io.OutputStream os = response.getOutputStream();
java.io.FileInputStream fis = new java.io.FileInputStream(
filenamedownload);
byte[] b = new byte[1024];
int i = 0;
while ((i = fis.read(b)) > 0) {
os.write(b, 0, i);
}
fis.close();
os.flush();
os.close();
} catch (Exception e) {

}

}

}

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

上传:

MyjspForm mf = (MyjspForm) form;// TODO Auto-generated method stub

FormFile fname=mf.getFname();

byte [] fn = fname.getFileData();

OutputStream out = new FileOutputStream("D:\"+fname.getFileName());

Date date = new Date();

String title = fname.getFileName();

String url = "d:\"+fname.getFileName();

Upload ul = new Upload();

ul.setDate(date);

ul.setTitle(title);

ul.setUrl(url);

UploadDAO uld = new UploadDAO();

uld.save(ul);

out.write(fn);

out.close();

下载:

DownloadForm downloadForm = (DownloadForm)form;

String fname = request.getParameter("furl");

FileInputStream fi = new FileInputStream(fname);

byte[] bt = new byte[fi.available()];

fi.read(bt);

//设置文件是下载还是打开以及打开的方式msdownload表示下载;设置字湖集,//主要是解决文件中的中文信息

response.setContentType("application/msdownload;charset=gbk");

//文件下载后的默认保存名及打开方式

String contentDisposition = "attachment; filename=" + "java.txt";

response.setHeader("Content-Disposition",contentDisposition);

//设置下载长度

response.setContentLength(bt.length);

ServletOutputStream sos = response.getOutputStream();

sos.write(bt);

return null;

⑦ jsp实现文件(doc,pdf,jpg,xls,ppt)上传下载功能.

当然可以了啊,你只需要在后台文件中增加读取文件信息,然后归类的方法就行了。
如果你是单纯用JSP然后就直接连接DB。。。。。直接在DAO里面实现吧,把文件信息分别读出来,然后insert到一张表里面去,并且,附上文件的path。也就是说,那张表里面至少得要有文件的路径,然后才是你所需要保存的信息。

⑧ 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上传文件的问题

用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即可。

热点内容
取票人的密码是什么 发布:2024-05-20 08:21:43 浏览:962
天猫帐号密码应输入什么 发布:2024-05-20 08:16:26 浏览:272
plsql异常处理 发布:2024-05-20 07:54:47 浏览:542
dreamweaver上传网页 发布:2024-05-20 07:51:24 浏览:462
拍摄车的分镜头脚本 发布:2024-05-20 07:50:15 浏览:137
mg名爵最高配置是哪个 发布:2024-05-20 07:45:11 浏览:376
辅助官网源码 发布:2024-05-20 07:31:48 浏览:866
androidbutton的属性 发布:2024-05-20 07:18:58 浏览:637
查找重复字段的sql 发布:2024-05-20 07:18:17 浏览:303
我的世界创造房子服务器 发布:2024-05-20 06:48:36 浏览:818