用java写一个从linux上传下载的系统

用java写一个从linux上传下载的系统,第1张

可以用ftp实现文件的上传下载,跟linux还是windows没有关系。

把linux作为remote server就可以了。

public static void backupUploadWithCommonsFTP(File fileToBeUpload) {

FTPClient f = new FTPClient()

boolean backupDirectoryExist = false

boolean fileToBeUploadExist = false

FTPFile backupDirectory = null

try {

f.connect(server.getServer())

f.login(server.getUsername(), server.getPassword())

FTPFile[] directories = f.listDirectories()

// Check for existence of backup directory

for (FTPFile file : directories) {

String filename = file.getName()

if (file.isDirectory() &&filename.equalsIgnoreCase("backup")) {

backupDirectory = file

backupDirectoryExist = true

break

}

}

if (!backupDirectoryExist) {

f.makeDirectory("backup")

}

// Check if file already exist on the server

f.changeWorkingDirectory("files")

FTPFile[] files = f.listFiles()

f.changeWorkingDirectory("backup")

String filePathToBeBackup="/home/user/backup/"

String prefix

String suffix

String fileNameToBeBackup

FTPFile fileReadyForBackup = null

f.setFileType(FTP.BINARY_FILE_TYPE)

f.setFileTransferMode(FTP.BINARY_FILE_TYPE)

for (FTPFile file : files) {

if (file.isFile() &&file.getName().equals(fileToBeUpload.getName())) {

prefix = FilenameUtils.getBaseName(file.getName())

suffix = ".".concat(FilenameUtils.getExtension(file.getName()))

fileNameToBeBackup = prefix.concat(Calendar.getInstance().getTime().toString().concat(suffix))

filePathToBeBackup = filePathToBeBackup.concat(fileNameToBeBackup)

fileReadyForBackup = file

fileToBeUploadExist = true

break

}

}

// If file already exist on the server create a backup from it otherwise just upload the file.

if(fileToBeUploadExist){

ByteArrayOutputStream outputStream = new ByteArrayOutputStream()

f.retrieveFile(fileReadyForBackup.getName(), outputStream)

InputStream is = new ByteArrayInputStream(outputStream.toByteArray())

if(f.storeUniqueFile(filePathToBeBackup, is)){

JOptionPane.showMessageDialog(null, "Backup succeeded.")

f.changeWorkingDirectory("files")

boolean reply = f.storeFile(fileToBeUpload.getName(), new FileInputStream(fileToBeUpload))

if(reply){

JOptionPane.showMessageDialog(null,"Upload succeeded.")

}else{

JOptionPane.showMessageDialog(null,"Upload failed after backup.")

}

}else{

JOptionPane.showMessageDialog(null,"Backup failed.")

}

}else{

f.changeWorkingDirectory("files")

f.setFileType(FTP.BINARY_FILE_TYPE)

f.enterLocalPassiveMode()

InputStream inputStream = new FileInputStream(fileToBeUpload)

ByteArrayInputStream in = new ByteArrayInputStream(FileUtils.readFileToByteArray(fileToBeUpload))

boolean reply = f.storeFile(fileToBeUpload.getName(), in)

System.out.println("Reply code for storing file to server: " + reply)

if(!f.completePendingCommand()) {

f.logout()

f.disconnect()

System.err.println("File transfer failed.")

System.exit(1)

}

if(reply){

JOptionPane.showMessageDialog(null,"File uploaded successfully without making backup." +

"\nReason: There wasn't any previous version of this file.")

}else{

JOptionPane.showMessageDialog(null,"Upload failed.")

}

}

//Logout and disconnect from server

in.close()

f.logout()

f.disconnect()

} catch (IOException e) {

e.printStackTrace()

}

}

既然使用了java,实现这种功能就与OS无关了,否则叫什么跨平台。其实用浏览器下载服务器端文件比较容易:

首先,要让用户能找到并选择文件(jsp里实现,部分代码)

String realPath=request.getSession().getServletContext().getRealPath("")+"/documents"//项目根目录下文件路径

File fileDir=new File(realPath)

String[] fileList=fileDir.list()//返回目录下文件名称数组

for(int i=0i<fileList.lengthi++){

//这里遍历出来要显示的文件名,加到td里,后面再加上个“下载”按钮

//使用隐藏input记录文件名和路径fileName,filePath

其次,提交下载请求并下载

使用form提交用户选择的文件名,Action中部分代码:

String fileName=req.getParameter("fileName")//HttpServletRequest req

String filePath=req.getParameter("filePath")

try {

FileDownload.Download(filePath+"/"+fileName, "attachment", res)

} catch (Exception e) {

e.printStackTrace()

}

下面是 FileDownload类:

package com.aerolink.aocs.util.fileUtil

import java.io.DataInputStream

import java.io.File

import java.io.FileInputStream

import java.io.FileNotFoundException

import java.io.IOException

import javax.servlet.ServletOutputStream

import javax.servlet.http.HttpServletResponse

/**

* <p>

* Title: FileDownload类

* </p>

* <p>

* Description: 实现文件下载功能

* </p>

* <p>

* 将文件名,HttpServletRequest,HttpServletRespons传给静态方法Download即可

* </p>

* <p>

* Copyright: Copyright (c) 2005

* </p>

* <p>

* Company: 北京天航信达信息技术有限公司

* </p>

*

* @author 陶源

* @version 2.0

*/

public class FileDownload {

/**

* @param fileName

* @param res

* @throws FileNotFoundException

* @throws IOException

*/

public static void Download(String fileName,

HttpServletResponse res)

throws FileNotFoundException, IOException {

String fileContentType = "application/octet-stream"

String fileDownloadType = "attachment"

long totalsize = 0

// 取得要传输的文件,实际应用是可以将文件路径以参数的形式传入

File f = new File(fileName)

// 取文件长度

long filelength = f.length()

byte[] b = new byte[1024]

// 设置文件输出

FileInputStream fin = new FileInputStream(f)

DataInputStream in = new DataInputStream(fin)

int pos = fileName.lastIndexOf(java.io.File.separator)

String fn = new String(fileName.substring(pos + 1).getBytes("gb2312"),

"ISO8859-1")

// 设置相应头信息,让下载的文件显示保存信息

res.setContentType(fileContentType)

res.setHeader("Content-Disposition", fileDownloadType + "filename=\""

+ fn + "\"")

// 确定长度

String filesize = Long.toString(filelength)

// 设置输出文件的长度

res.setHeader("Content-Length", filesize)

// 取得输出流

ServletOutputStream servletOut = res.getOutputStream()

// 发送文件数据,每次1024字节,最后一次单独计算

while (totalsize <filelength) {

totalsize += 1024

if (totalsize >filelength) {

// 最后一次传送的字节数

byte[] leftpart = new byte[1024 - (int) (totalsize - filelength)]

// 读入字节数组

in.readFully(leftpart)

// 写入输出流

servletOut.write(leftpart)

} else {

// 读入1024个字节到字节数组 b

in.readFully(b)

// 写和输出流

servletOut.write(b)

}

}

servletOut.close()

}

/**

* @param fileName

* @param fileDownloadType

* @param res

* @throws FileNotFoundException

* @throws IOException

*/

public static void Download(String fileName, String fileDownloadType,

HttpServletResponse res)

throws FileNotFoundException, IOException {

String fileContentType = null

if (fileName.endsWith(".doc")) {

fileContentType = "application/msword"

} else if (fileName.endsWith(".pdf")) {

fileContentType = "application/pdf"

} else if (fileName.endsWith(".xls")) {

fileContentType = "application/vnd-ms-excel"

} else if (fileName.endsWith(".txt")) {

fileContentType = "text/plain"

} else {

fileContentType = "application/octet-stream"

}

long totalsize = 0

// 取得要传输的文件,实际应用是可以将文件路径以参数的形式传入

File f = new File(fileName)

// 取文件长度

long filelength = f.length()

byte[] b = new byte[1024]

// 设置文件输出流

FileInputStream fin = new FileInputStream(f)

DataInputStream in = new DataInputStream(fin)

int pos = fileName.lastIndexOf(java.io.File.separator)

String fn = new String(fileName.substring(pos + 1).getBytes("gb2312"),

"ISO8859-1")

// 设置相应头信息,让下载的文件显示保存信息

res.setContentType(fileContentType)

res.setHeader("Content-Disposition", fileDownloadType + "filename=\""

+ fn + "\"")

// 确定长度

String filesize = Long.toString(filelength)

// 设置输出文件的长度

res.setHeader("Content-Length", filesize)

// 取得输出流

ServletOutputStream servletOut = res.getOutputStream()

// 发送文件数据,每次1024字节,最后一次单独计算

while (totalsize <filelength) {

totalsize += 1024

if (totalsize >filelength) {

// 最后一次传送的字节数

byte[] leftpart = new byte[1024 - (int) (totalsize - filelength)]

// 读入字节数组

in.readFully(leftpart)

// 写入输出流

servletOut.write(leftpart)

} else {

// 读入1024个字节到字节数组 b

in.readFully(b)

// 写和输出流

servletOut.write(b)

}

}

servletOut.close()

}

}


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/yw/9014614.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-04-24
下一篇 2023-04-24

发表评论

登录后才能评论

评论列表(0条)

保存