當前位置:首頁 » 文件管理 » jsp文件下載上傳

jsp文件下載上傳

發布時間: 2022-10-05 14:18:12

❶ 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上傳下載文件的路徑問題

jsp上傳下載文件的路徑是在伺服器建立指定路徑如下:
//接收上傳文件內容中臨時文件的文件名
String tempFileName = new String("tempFileName");
//tempfile 對象指向臨時文件
File tempFile = new File("D:/"+tempFileName);
//outputfile 文件輸出流指向這個臨時文件
FileOutputStream outputStream = new FileOutputStream(tempFile);
//得到客服端提交的所有數據
InputStream fileSourcel = request.getInputStream();
//將得到的客服端數據寫入臨時文件
byte b[] = new byte[1000];
int n ;
while ((n=fileSourcel.read(b))!=-1){
outputStream.write(b,0,n);
}

//關閉輸出流和輸入流
outputStream.close();
fileSourcel.close();

//randomFile對象指向臨時文件
RandomAccessFile randomFile = new RandomAccessFile(tempFile,"r");
//讀取臨時文件的第一行數據
randomFile.readLine();
//讀取臨時文件的第二行數據,這行數據中包含了文件的路徑和文件名
String filePath = randomFile.readLine();
//得到文件名
int position = filePath.lastIndexOf('\\');
CodeToString codeToString = new CodeToString();
String filename = codeToString.codeString(filePath.substring(position,filePath.length()-1));
//重新定位讀取文件指針到文件頭
randomFile.seek(0);
//得到第四行回車符的位置,這是上傳文件數據的開始位置
long forthEnterPosition = 0;
int forth = 1;
while((n=randomFile.readByte())!=-1&&(forth<=4)){
if(n=='\n'){
forthEnterPosition = randomFile.getFilePointer();
forth++;
}
}

//生成上傳文件的目錄
File fileupLoad = new File("D:/work space/JSP workspace/jsp_servlet_upAndLoad/file","upLoad");
fileupLoad.mkdir();
//saveFile 對象指向要保存的文件
File saveFile = new File("D:/work space/JSP workspace/jsp_servlet_upAndLoad/file/upLoad",filename);
RandomAccessFile randomAccessFile = new RandomAccessFile(saveFile,"rw");
//找到上傳文件數據的結束位置,即倒數第四行
randomFile.seek(randomFile.length());
long endPosition = randomFile.getFilePointer();
int j = 1;
while((endPosition>=0)&&(j<=4)){
endPosition--;
randomFile.seek(endPosition);
if(randomFile.readByte()=='\n'){
j++;
}
}

//從上傳文件數據的開始位置到結束位置,把數據寫入到要保存的文件中
randomFile.seek(forthEnterPosition);
long startPoint = randomFile.getFilePointer();
while(startPoint<endPosition){
randomAccessFile.write(randomFile.readByte());
startPoint = randomFile.getFilePointer();
}
//關閉文件輸入、輸出
randomAccessFile.close();
randomFile.close();
tempFile.delete();

jsp文件下載選擇路徑:
//要下載的文件
File fileload = new File("D:/work space/JSP workspace/jsp_servlet_upAndLoad/file/upLoad",filename);

❸ jsp 文件的上傳與下載 要求對文件的類型、大小進行選擇判斷

你下載一個 jspsmartupload 里不是有七個例子,其中一個就是了,你看看

❹ jsp怎麼下載上傳文件

去apache網站上下個common-fileupload上傳組件用就可以了!

❺ 我想用jsp語言編寫的網頁中實現文件上傳、下載的功能,請問完整的代碼怎麼寫,盡量是最簡單的,謝謝

<input type='file'>
然後設置form的 enctype= "multipart/form-data "
然後後台從HttpServletRequest裡面取文件出來就ok了!

❻ 如何用JSP實現文件的上傳和下載,要對資料庫進行什麼操作

你的表單呢?他的意思等你上傳完成後,你要把文件信息更新到資料庫,當你在向用戶展示時,只需要查詢數據即可。可以再資料庫建一個表,吧相應欄位存起來,最重要的是存上你的圖片路徑和名字。

❼ 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項目中涉及文件的上傳和下載怎麼實現

你是用什麼框架,如果裡面有struts的話可以用struts自帶有上傳下載的功能,只需要寫代碼就好了,如果需要加我987781070,如果沒有用到struts可以用ajax實現,這個自己網路就好了,很多案例的!

❾ 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";
}
}

熱點內容
佛加密轉碼 發布:2022-11-27 23:21:57 瀏覽:385
sn是密碼還是什麼 發布:2022-11-27 23:19:21 瀏覽:388
那夜4次ftp 發布:2022-11-27 23:16:12 瀏覽:117
oppo手機加密怎麼解除 發布:2022-11-27 23:13:05 瀏覽:105
安卓抖音如何直播電影 發布:2022-11-27 23:11:39 瀏覽:939
我的世界伺服器如何放置插件 發布:2022-11-27 23:11:32 瀏覽:379
在家怎麼訪問辦公室的伺服器ip 發布:2022-11-27 23:07:34 瀏覽:185
如何改變圖片存儲大小 發布:2022-11-27 23:06:20 瀏覽:687
安卓7以下怎麼查看wifi密碼 發布:2022-11-27 23:05:13 瀏覽:412
汽車漆怎麼看配置 發布:2022-11-27 23:03:22 瀏覽:363