本文目錄一覽:
- 1、java怎麼把文件傳輸到file
- 2、java中怎樣上傳文件
- 3、java 服務器與客戶端的文件傳輸
- 4、javaweb 怎麼樣將本地文件傳輸到遠程服務器
- 5、用Java實現在兩台電腦之間的文件傳輸
- 6、java怎麼把文件傳輸到服務器
java怎麼把文件傳輸到file
common-fileupload是jakarta項目組開發的一個功能很強大的上傳文件組件
下面先介紹上傳文件到服務器(多文件上傳):
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
import java.util.regex.*;
import org.apache.commons.fileupload.*;
public class upload extends HttpServlet {
private static final String CONTENT_TYPE = “text/html; charset=GB2312”;
//Process the HTTP Post request
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType(CONTENT_TYPE);
PrintWriter out=response.getWriter();
try {
DiskFileUpload fu = new DiskFileUpload();
// 設置允許用戶上傳文件大小,單位:字節,這裡設為2m
fu.setSizeMax(2*1024*1024);
// 設置最多只允許在內存中存儲的數據,單位:字節
fu.setSizeThreshold(4096);
// 設置一旦文件大小超過getSizeThreshold()的值時數據存放在硬盤的目錄
fu.setRepositoryPath(“c://windows//temp”);
//開始讀取上傳信息
List fileItems = fu.parseRequest(request);
// 依次處理每個上傳的文件
Iterator iter = fileItems.iterator();
//正則匹配,過濾路徑取文件名
String regExp=”.+////(.+)$”;
//過濾掉的文件類型
String[] errorType={“.exe”,”.com”,”.cgi”,”.asp”};
Pattern p = Pattern.compile(regExp);
while (iter.hasNext()) {
FileItem item = (FileItem)iter.next();
//忽略其他不是文件域的所有表單信息
if (!item.isFormField()) {
String name = item.getName();
long size = item.getSize();
if((name==null||name.equals(“”)) size==0)
continue;
Matcher m = p.matcher(name);
boolean result = m.find();
if (result){
for (int temp=0;tempERRORTYPE.LENGTH;TEMP++){
if (m.group(1).endsWith(errorType[temp])){
throw new IOException(name+”: wrong type”);
}
}
try{
//保存上傳的文件到指定的目錄
//在下文中上傳文件至數據庫時,將對這裡改寫
item.write(new File(“d://” + m.group(1)));
out.print(name+” “+size+””);
}
catch(Exception e){
out.println(e);
}
}
else
{
throw new IOException(“fail to upload”);
}
}
}
}
catch (IOException e){
out.println(e);
}
catch (FileUploadException e){
out.println(e);
}
}
}
現在介紹上傳文件到服務器,下面只寫出相關代碼:
以sql2000為例,表結構如下:
字段名:name filecode
類型: varchar image
數據庫插入代碼為:PreparedStatement pstmt=conn.prepareStatement(“insert into test values(?,?)”);
代碼如下:
。。。。。。
try{
這段代碼如果不去掉,將一同寫入到服務器中
//item.write(new File(“d://” + m.group(1)));
int byteread=0;
//讀取輸入流,也就是上傳的文件內容
InputStream inStream=item.getInputStream();
pstmt.setString(1,m.group(1));
pstmt.setBinaryStream(2,inStream,(int)size);
pstmt.executeUpdate();
inStream.close();
out.println(name+” “+size+” “);
}
。。。。。。
這樣就實現了上傳文件至數據庫
java中怎樣上傳文件
Java代碼實現文件上傳
FormFile file=manform.getFile();
String newfileName = null;
String newpathname=null;
String fileAddre=”/numUp”;
try {
InputStream stream = file.getInputStream();// 把文件讀入
String filePath = request.getRealPath(fileAddre);//取系統當前路徑
File file1 = new File(filePath);//添加了自動創建目錄的功能
((File) file1).mkdir();
newfileName = System.currentTimeMillis()
+ file.getFileName().substring(
file.getFileName().lastIndexOf(‘.’));
ByteArrayOutputStream baos = new ByteArrayOutputStream();
OutputStream bos = new FileOutputStream(filePath + “/”
+ newfileName);
newpathname=filePath+”/”+newfileName;
System.out.println(newpathname);
// 建立一個上傳文件的輸出流
System.out.println(filePath+”/”+file.getFileName());
int bytesRead = 0;
byte[] buffer = new byte[8192];
while ((bytesRead = stream.read(buffer, 0, 8192)) != -1) {
bos.write(buffer, 0, bytesRead);// 將文件寫入服務器
}
bos.close();
stream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
java 服務器與客戶端的文件傳輸
可以直接通過流的形式上傳或者下載。
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Properties;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpException;
import hkrt.b2b.view.util.Log;
import java.util.Vector;
import zn.ccfccb.util.CCFCCBUtil;
/**
*/
public class CCFCCBSftp {
/**
* 連接sftp服務器
*
* @return
*/
public static ChannelSftp connect() {
ChannelSftp sftp = null;
try {
JSch jsch = new JSch();
jsch.getSession(CCFCCBUtil.CCFCCBHOSTNAME, CCFCCBUtil.CCFCCBHOSTNAME, 22);
Session sshSession = jsch.getSession(CCFCCBUtil.CCFCCBLOGINNAME, CCFCCBUtil.CCFCCBHOSTNAME, 22);
System.out.println(“Session created.”);
sshSession.setPassword(CCFCCBUtil.CCFCCBLOGINPASSWORD);
Properties sshConfig = new Properties();
sshConfig.put(“StrictHostKeyChecking”, “no”);
sshSession.setConfig(sshConfig);
sshSession.connect();
System.out.println(“Session connected.”);
System.out.println(“Opening Channel.”);
Channel channel = sshSession.openChannel(“sftp”);
channel.connect();
sftp = (ChannelSftp) channel;
System.out.println(“Connected to ” + CCFCCBUtil.CCFCCBHOSTNAME + “.”);
} catch (Exception e) {
}
return sftp;
}
/**
* 連接sftp服務器
*
* @param host 主機
* @param port 端口
* @param username 用戶名
* @param password 密碼
* @return
*/
public static ChannelSftp connect(String host, int port, String username,
String password) {
ChannelSftp sftp = null;
try {
JSch jsch = new JSch();
jsch.getSession(CCFCCBUtil.CCFCCBHOSTNAME, CCFCCBUtil.CCFCCBHOSTNAME, 22);
Session sshSession = jsch.getSession(CCFCCBUtil.CCFCCBLOGINNAME, host, port);
System.out.println(“Session created.”);
sshSession.setPassword(CCFCCBUtil.CCFCCBLOGINPASSWORD);
Properties sshConfig = new Properties();
sshConfig.put(“StrictHostKeyChecking”, “no”);
sshSession.setConfig(sshConfig);
sshSession.connect();
System.out.println(“Session connected.”);
System.out.println(“Opening Channel.”);
Channel channel = sshSession.openChannel(“sftp”);
channel.connect();
sftp = (ChannelSftp) channel;
System.out.println(“Connected to ” + host + “.”);
} catch (Exception e) {
}
return sftp;
}
/**
* 上傳文件
*
* @param directory 上傳的目錄
* @param uploadFile 要上傳的文件
* @param sftp
*/
public void upload(String directory, String uploadFile, ChannelSftp sftp) {
try {
s;
File file = new File(uploadFile);
s(new FileInputStream(file), file.getName());
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 下載文件
*
* @param directory 下載目錄
* @param downloadFile 下載的文件
* @param saveFile 存在本地的路徑
* @param sftp
* @return
*/
public static String download(String directory, String downloadFile, String saveFile, ChannelSftp sftp) {
try {
s;
File file = new File(saveFile);
FileOutputStream fos = new FileOutputStream(file);
s(downloadFile, fos);
s;
fos.close();
} catch (Exception e) {
Log.info(“下載文件過程出錯:” + e.getMessage());
return “false”;
}
return “true”;
}
/**
* 刪除文件
*
* @param directory 要刪除文件所在目錄
* @param deleteFile 要刪除的文件
* @param sftp
*/
public void delete(String directory, String deleteFile, ChannelSftp sftp) {
try {
s;
s;
} catch (Exception e) {
}
}
/**
* 列出目錄下的文件
*
* @param directory 要列出的目錄
* @param sftp
* @return
* @throws SftpException
*/
public Vector listFiles(String directory, ChannelSftp sftp) throws SftpException {
return s;
}
public static void main(String[] args) {
CCFCCBSftp sf = new CCFCCBSftp();
String host = CCFCCBUtil.CCFCCBHOSTNAME;
int port = 22;
String username = CCFCCBUtil.CCFCCBLOGINNAME;
String password = CCFCCBUtil.CCFCCBLOGINPASSWORD;
String directory = “/ccfccb/904999900099/download/”;
//String uploadFile = “D:\\tmp\\upload.txt”;
String downloadFile = “CCF_904999900099_20150317_0001.zip”;
String saveFile = CCFCCBUtil.CCFCCBUploadFilePath + “//” + “CCF_904999900099_20150317_0001.zip”;
//String deleteFile = “delete.txt”;
ChannelSftp sftp = CCFCCBS(host, port, username, password);
//sf.upload(directory, uploadFile, sftp);
CCFCCBS(directory, downloadFile, saveFile, sftp);
//sf.delete(directory, deleteFile, sftp);
try {
s;
// s(“ss”);
System.out.println(“finished”);
} catch (Exception e) {
}
}
}
javaweb 怎麼樣將本地文件傳輸到遠程服務器
可以通過JDK自帶的API實現,如下代碼:
package com.cloudpower.util;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import sun.net.TelnetInputStream;
import sun.net.TelnetOutputStream;
import sun.net.;
/**
* Java自帶的API對FTP的操作
* @Title:
*/
public class Ftp {
/**
* 本地文件名
*/
private String localfilename;
/**
* 遠程文件名
*/
private String remotefilename;
/**
* FTP客戶端
*/
private FtpClient ftpClient;
/**
* 服務器連接
* @param ip 服務器IP
* @param port 服務器端口
* @param user 用戶名
* @param password 密碼
* @param path 服務器路徑
* @date 2012-7-11
*/
public void connectServer(String ip, int port, String user,
String password, String path) {
try {
/* ******連接服務器的兩種方法*******/
//第一種方法
// ftpClient = new FtpClient();
// ftpClient.openServer(ip, port);
//第二種方法
ftpClient = new FtpClient(ip);
ftpClient.login(user, password);
// 設置成2進制傳輸
ftpClient.binary();
System.out.println(“login success!”);
if (path.length() != 0){
//把遠程系統上的目錄切換到參數path所指定的目錄
ftpClient.cd(path);
}
ftpClient.binary();
} catch (IOException ex) {
ex.printStackTrace();
throw new RuntimeException(ex);
}
}
public void closeConnect() {
try {
ftpClient.closeServer();
System.out.println(“disconnect success”);
} catch (IOException ex) {
System.out.println(“not disconnect”);
ex.printStackTrace();
throw new RuntimeException(ex);
}
}
public void upload(String localFile, String remoteFile) {
this.localfilename = localFile;
this.remotefilename = remoteFile;
TelnetOutputStream os = null;
FileInputStream is = null;
try {
//將遠程文件加入輸出流中
os = ftpClient.put(this.remotefilename);
//獲取本地文件的輸入流
File file_in = new File(this.localfilename);
is = new FileInputStream(file_in);
//創建一個緩衝區
byte[] bytes = new byte[1024];
int c;
while ((c = is.read(bytes)) != -1) {
os.write(bytes, 0, c);
}
System.out.println(“upload success”);
} catch (IOException ex) {
System.out.println(“not upload”);
ex.printStackTrace();
throw new RuntimeException(ex);
} finally{
try {
if(is != null){
is.close();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if(os != null){
os.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public void download(String remoteFile, String localFile) {
TelnetInputStream is = null;
FileOutputStream os = null;
try {
//獲取遠程機器上的文件filename,藉助TelnetInputStream把該文件傳送到本地。
is = ftpClient.get(remoteFile);
File file_in = new File(localFile);
os = new FileOutputStream(file_in);
byte[] bytes = new byte[1024];
int c;
while ((c = is.read(bytes)) != -1) {
os.write(bytes, 0, c);
}
System.out.println(“download success”);
} catch (IOException ex) {
System.out.println(“not download”);
ex.printStackTrace();
throw new RuntimeException(ex);
} finally{
try {
if(is != null){
is.close();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if(os != null){
os.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public static void main(String agrs[]) {
String filepath[] = { “/temp/aa.txt”, “/temp/regist.log”};
String localfilepath[] = { “C:\\tmp\\1.txt”,”C:\\tmp\\2.log”};
Ftp fu = new Ftp();
/*
* 使用默認的端口號、用戶名、密碼以及根目錄連接FTP服務器
*/
fu.connectServer(“127.0.0.1”, 22, “anonymous”, “IEUser@”, “/temp”);
//下載
for (int i = 0; i filepath.length; i++) {
fu.download(filepath[i], localfilepath[i]);
}
String localfile = “E:\\號碼.txt”;
String remotefile = “/temp/哈哈.txt”;
//上傳
fu.upload(localfile, remotefile);
fu.closeConnect();
}
}
用Java實現在兩台電腦之間的文件傳輸
使用Socket可以做到,不過直接編程一般都是在局域網內,如果要在不同局域網間通信,需要使用一台有公網IP的服務器,可以電腦A和電腦B同時連接服務器,然後A向服務器傳遞文件,服務器再將文件轉發電腦B。也可以使用打洞的方式使A、B互聯,此時服務器的作用是輔助打洞。A、B向服務器發送信息後socket不要關閉(假設使用10989端口),同時使用Serversocket綁定監聽相同的端口(監聽10989端口)。在java中有參數可以做到,具體方法請自行百度。服務器獲取到A、B的外網地址和端口,將A的外網地址信息發送給B、將B的外網地址信息發送給A。然後使用A沒有關閉的Socket向B發送一組信息(此時連接會失敗,但是B的路由表上已經記錄了A的信息),發送後A向服務器發送消息,服務器告訴B A已經發送消息。然後B使用未關閉的socket向A發送消息,就和A上監聽的ServerSocket取得連接了。之後就可以互相傳遞數據。
java怎麼把文件傳輸到服務器
String realpath = ServletActionContext.getServletContext().getRealPath(“/upload”) ;//獲取服務器路徑
String[] targetFileName = uploadFileName;
for (int i = 0; i upload.length; i++) {
File target = new File(realpath, targetFileName[i]);
FileUtils.copyFile(upload[i], target);
//這是一個文件複製類copyFile()裡面就是IO操作,如果你不用這個類也可以自己寫一個IO複製文件的類
}
其中private File[] upload;// 實際上傳文件
private String[] uploadContentType; // 文件的內容類型
private String[] uploadFileName; // 上傳文件名
這三個參數必須這樣命名,因為文件上傳控件默認是封裝了這3個參數的,且在action裡面他們應有get,set方法
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/285793.html