當前位置:首頁 » 文件管理 » jsp上傳目錄

jsp上傳目錄

發布時間: 2022-12-06 11:43:27

❶ 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把本地的文件夾上傳到ftp伺服器

前段時間做了一個文件上傳ftp功能,你參照一下

package com.ftp.upload;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;

public class FTPUpload {
private FTPClient ftpClient = null;

private OutputStream outSteam = null;

/**
* ftp伺服器地址
*/
private String hostname = "192.168.1.2";
/**
* ftp伺服器埠
*/
int port = 21;
/**
* 登錄名
*/
private String username = "admin";

/**
* 登錄密碼
*/
private String password = "admin";

/**
* 需要訪問的遠程目錄
*/
private String remoteDir = "/home/demo";

public FTPUpload() { }

public FTPUpload(String hostname, int port, String username, String password, String remoteDir){
this.hostname = hostname;
this.port = port;
this.username = username;
this.password = password;
this.remoteDir = remoteDir;

}
/**
* 連接FTP伺服器 並登錄
* @param hostName FTP伺服器hostname
* @param port FTP伺服器埠
* @param username FTP登錄賬號
* @param password FTP登錄密碼
*/
private FTPClient connectFTPServer() {
try {
//1.創建FTPClient對象
ftpClient = new FTPClient();
//2.連接FTP伺服器
// 如果採用默認埠,可以使用ftp.connect(url)的方式直接連接FTP伺服器
ftpClient.connect(hostname, port); //鏈接到ftp伺服器
// System.out.println("連接到ftp伺服器地址 --> ftp://" + hostName + ":" + port + " 成功..開始登錄");

//3.判斷連接ftp伺服器是否成功
int reply = ftpClient.getReplyCode();
// System.out.println("以2開頭的返回值就會為真:" + reply);
//以2開頭的返回值就會為真
if (!FTPReply.isPositiveCompletion(reply)) {
ftpClient.disconnect();
return null;
}

//4.登錄FTP伺服器.用戶名 密碼
ftpClient.login(username, password);
System.out.println("登錄成功." );

return ftpClient;
} catch (Exception e) {
e.printStackTrace();
ftpClient = null;
return ftpClient;
}
}

/**
* 向FTP伺服器上傳文件
* @param filePathName 上傳文件的全路徑名稱
* @return 成功返回true,否則返回false
*/
public boolean uploadFile(String filePathName) {
// 初始表示上傳失敗
boolean success = false;
try {
// 創建FTPClient對象
ftpClient = connectFTPServer();
//創建文件夾
boolean flag = ftpClient.makeDirectory(remoteDir);
if(flag) {
System.out.println("創建文件夾:" + remoteDir );
}

// 轉到指定上傳目錄
boolean flag0 = ftpClient.changeWorkingDirectory(remoteDir);
// 將上傳文件存儲到指定目錄
if(filePathName == null || filePathName.length() == 0){
return success;
}
String filename = filePathName.substring(filePathName.replace("\\", "/").lastIndexOf("/") + 1, filePathName.length());

InputStream input = new FileInputStream(new File(filePathName));

// ftpClient.setBufferSize(1024);
// ftpClient.setControlEncoding("GBK");
// ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);//設置文件類型

boolean flag1 = ftpClient.storeFile(filename, input);
System.out.println("轉到指定上傳目錄:" + flag0 + " 將上傳文件存儲到指定目錄:" + flag1);

input.close(); // 關閉輸入流
ftpClient.logout(); // 退出ftp
success = true; // 表示上傳成功

} catch (Exception e) {
e.printStackTrace();
} finally {
if (ftpClient.isConnected()) {
try {
ftpClient.disconnect();
} catch (IOException ioe) {
}
}
}
return success;
}

/**
* 從FTP伺服器指定目錄下載文件 到本地目錄中 OK
* @param fileName 要下載的文件名
* @param localPath 下載後保存到本地的路徑
* @param showlist 下載時是否顯示列表 ( true 顯示 )
* @return
*/
public boolean downFile(String fileName, String localPath, boolean showlist) {
// 初始表示下載失敗
boolean success = false;
if(fileName == null || fileName.length() == 0 || localPath == null || localPath.length() == 0){
return success;
}
try {
File file = new File(localPath);

if(!file.isDirectory()){
file.mkdir();
}
// 創建FTPClient對象
ftpClient = connectFTPServer();
// 轉到指定下載目錄
boolean flag = ftpClient.changeWorkingDirectory(remoteDir);
if(!flag) {
System.out.println("目錄:" + remoteDir +"不存在!");
return success;
}
// 列出該目錄下所有文件
FTPFile[] remoteFiles = ftpClient.listFiles();

// 遍歷所有文件,找到指定的文件
if(showlist){
System.out.println("目錄" + remoteDir + "下的文件:");
}

for (FTPFile ftpFile : remoteFiles) {
String name = ftpFile.getName();
if(showlist){
long length = ftpFile.getSize();
String readableLength = FileUtils.byteCountToDisplaySize(length);
System.out.println(name + ":\t\t" + readableLength);
}

if (name.equals(fileName)) {
// 根據絕對路徑初始化文件
File localFile = new File(localPath + "/" + name);
// 輸出流
OutputStream is = new FileOutputStream(localFile);
// 下載文件
ftpClient.retrieveFile(name, is);
is.close();
}
}
// 退出ftp
ftpClient.logout();
// 下載成功
success = true;
} catch (IOException e) {
e.printStackTrace();
} finally {
if (ftpClient.isConnected()) {
try {
ftpClient.disconnect();
} catch (IOException ioe) {
}
}
}
return success;
}

/**
* 顯示FTP伺服器指定文件夾中的文件及大小 OK
* @return
*/
private boolean showFileList() {
// 初始表示失敗
boolean success = false;
try {
ftpClient = connectFTPServer();
FTPFile[] remoteFiles = null;
// 轉到指定下載目錄
boolean flag = ftpClient.changeWorkingDirectory(remoteDir);
if(!flag) {
System.out.println("目錄:" + remoteDir +"不存在!");
return success;
} else{
remoteFiles = ftpClient.listFiles(remoteDir);
System.out.println("目錄" + remoteDir + "下的文件:");
}

if(remoteFiles != null) {
for(int i=0;i < remoteFiles.length; i++){
String name = remoteFiles[i].getName();
long length = remoteFiles[i].getSize();
String readableLength = FileUtils.byteCountToDisplaySize(length);
System.out.println(name + ":\t\t" + readableLength);
}
}
// 表示成功
success = true;
} catch (Exception e) {
e.printStackTrace();
} finally {
//使用IO包關閉流
IOUtils.closeQuietly(outSteam);
try {
ftpClient.disconnect();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
return success;
}
public static void main(String[] args) {
FTPUpload ftp = new FTPUpload();
ftp.uploadFile("c:////test////bgssp.jar");
}
}

❸ jsp將圖片等文件上傳到伺服器根目錄下,讀取二進制流存入mysql怎麼樣實現

插入圖片到資料庫代碼片段
private Connection conn = null;
private PreparedStatement pstmt = null;
private static final String sql = "INSERT INTO images_info(image_id,image_name,image_size,image_date,image_type,image_description,author,image_data)VALUES(null,?,?,now(),?,?,?,?)";
public boolean addPhoto(ImageVo imageVo) {
boolean flag = false;
try{
//將文件轉換為流文件
InputStream photoStream = new FileInputStream(imageVo.getImageData());
//獲取資料庫連接
conn = ConnectionFactory.getConnection();
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, imageVo.getImageName());
pstmt.setInt(2, imageVo.getImageSize());
pstmt.setString(3 , "jpg");//圖片類型
pstmt.setString(4, imageVo.getDescription());
pstmt.setString(5, imageVo.getAuthor());
pstmt.setBinaryStream(6, photoStream, (int)imageVo.getImageData().length());
int row = pstmt.executeUpdate();
if(row == 1){
flag = true;
}
}catch(FileNotFoundException fe){
fe.printStackTrace();
}catch(SQLException e){
e.printStackTrace();
}finally{
if(null != pstmt){
try{pstmt.close();}
catch(SQLException e){
e.printStackTrace();
}
}
if(null != conn){
try{conn.close();}
catch(SQLException e){
e.printStackTrace();
}
}
}
return flag;
}

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

熱點內容
怎麼自己買2手伺服器 發布:2025-07-24 10:45:13 瀏覽:351
腳本打招募 發布:2025-07-24 10:40:56 瀏覽:556
如何進入一個人多的伺服器 發布:2025-07-24 10:34:58 瀏覽:302
漯河ftp伺服器 發布:2025-07-24 10:15:41 瀏覽:501
android文件拷貝 發布:2025-07-24 10:12:02 瀏覽:360
ios解壓縮zip 發布:2025-07-24 10:11:22 瀏覽:244
微信的安卓夜間模式怎麼設置 發布:2025-07-24 09:04:19 瀏覽:753
安卓手機丟了怎麼定位 發布:2025-07-24 09:04:17 瀏覽:216
psvproxy伺服器怎麼設置 發布:2025-07-24 08:36:40 瀏覽:194
超越腳本 發布:2025-07-24 08:36:37 瀏覽:809