當前位置:首頁 » 文件管理 » 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 06:48:36 瀏覽:818
小米筆記本存儲不夠 發布:2024-05-20 06:32:53 瀏覽:784
dirt5需要什麼配置 發布:2024-05-20 06:02:58 瀏覽:543
怎麼把電腦鎖上密碼 發布:2024-05-20 05:19:09 瀏覽:985
安卓為什麼連上wifi後沒有網路 發布:2024-05-20 05:17:50 瀏覽:419
安卓usb在設置哪裡 發布:2024-05-20 05:03:03 瀏覽:187
綏化編程 發布:2024-05-20 04:59:44 瀏覽:991
基本原理和從頭計演算法 發布:2024-05-20 04:50:32 瀏覽:30
配置情況指的是什麼 發布:2024-05-20 04:48:14 瀏覽:497
那個程序用來編譯源文件 發布:2024-05-20 04:46:45 瀏覽:551