1、java中怎麼把文件上傳到伺服器的指定路徑
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;temp<ERRORTYPE.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+" ");
}
。。。。。。
這樣就實現了上傳文件至資料庫
2、java中怎麼把文件上傳到伺服器的指定路徑?
文件從本地到伺服器的功能,其實是為了解決目前瀏覽器不支持獲取本地文件全路徑。不得已而想到上傳到伺服器的固定目錄,從而方便項目獲取文件,進而使程序支持EXCEL批量導入數據。
java中文件上傳到伺服器的指定路徑的代碼:
在前台界面中輸入:
<form method="post" enctype="multipart/form-data" action="../manage/excelImport.do">
請選文件:<input type="file" name="excelFile">
<input type="submit" value="導入" onclick="return impExcel();"/>
</form>
action中獲取前台傳來數據並保存
/**
* excel 導入文件
* @return
* @throws IOException
*/
@RequestMapping("/usermanager/excelImport.do")
public String excelImport(
String filePath,
MultipartFile excelFile,HttpServletRequest request) throws IOException{
log.info("<<<<<<action:{} Method:{} start>>>>>>","usermanager","excelImport" );
if (excelFile != null){
String filename=excelFile.getOriginalFilename();
String a=request.getRealPath("u/cms/www/201509");
SaveFileFromInputStream(excelFile.getInputStream(),request.getRealPath("u/cms/www/201509"),filename);//保存到伺服器的路徑
}
log.info("<<<<<<action:{} Method:{} end>>>>>>","usermanager","excelImport" );
return "";
}
/**
* 將MultipartFile轉化為file並保存到伺服器上的某地
*/
public void SaveFileFromInputStream(InputStream stream,String path,String savefile) throws IOException
{
FileOutputStream fs=new FileOutputStream( path + "/"+ savefile);
System.out.println("------------"+path + "/"+ savefile);
byte[] buffer =new byte[1024*1024];
int bytesum = 0;
int byteread = 0;
while ((byteread=stream.read(buffer))!=-1)
{
bytesum+=byteread;
fs.write(buffer,0,byteread);
fs.flush();
}
fs.close();
stream.close();
}
3、怎樣通過java實現伺服器上文件下載?
用HttpClient(commons httpclient)包,模擬一個Get請求,發送到網址172.16.30.230/文件地址。這個文件地址不能是E/Map/123.txt,必須是暴露在伺服器中的應用里的。就像你寫的應用里的一個jsp頁面的目錄。
成功發送get請求後,就會得到response,裡面有流。就是你下載的文件,然後可以通過FileOutputStream,指定你輸出目錄,寫到磁碟上。
4、java 如何在使用java類 從客戶端下載伺服器上的文件
js 做不到 copy 到客戶端指定位置
如果說的是java的話, 可以做到
import java.io.FileNotFoundException;5、java 讀取伺服器上的文件
http的話就用httpclient。open後,可以返回一個InputStream。這個就是你要讀到文件流。
原理的話,參考你用瀏覽器打開這個鏈接顯示的內容。
這個返回的是一個HTML網頁,需要你解析出裡面的文字(一般來說取body中間的內容就行)
其實對於這種文件一般用FTP來下載的。樓上寫的那個不對,哈哈。
需要的話自己最好去查一下,怎麼用,我有代碼,不過告訴你的話也不太好?
URL url = new URL("http://你的地址");
URLConnection connection = url.openConnection();
InputStream is = connection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is,"gb2312"));
下面就是解析這個字元串來,自己來吧
6、java如何在本地直接打開伺服器上面指定路徑的文件 要詳細一點的,最好是有詳細程序的
思路:把伺服器上的文件下載到本地電腦,然後打開。
URL url = new URL("http://...........");
BuffereInputStream bis = new BufferedInputStream(url.openConnection().getOutputStream());
先把文件讀取到本地,然後從本地打開。
7、java中如何實現從客戶端發送文件到伺服器端
伺服器端源碼:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
/**
*
* 文件名:ServerReceive.java
* 實現功能:作為伺服器接收客戶端發送的文件
*
* 具體實現過程:
* 1、建立SocketServer,等待客戶端的連接
* 2、當有客戶端連接的時候,按照雙方的約定,這時要讀取一行數據
* 其中保存客戶端要發送的文件名和文件大小信息
* 3、根據文件名在本地創建文件,並建立好流通信
* 4、循環接收數據包,將數據包寫入文件
* 5、當接收數據的長度等於提前文件發過來的文件長度,即表示文件接收完畢,關閉文件
* 6、文件接收工作結束
public class ServerReceive {
public static void main(String[] args) {
/**與伺服器建立連接的通信句柄*/
ServerSocket ss = null;
Socket s = null;
/**定義用於在接收後在本地創建的文件對象和文件輸出流對象*/
File file = null;
FileOutputStream fos = null;
/**定義輸入流,使用socket的inputStream對數據包進行輸入*/
InputStream is = null;
/**定義byte數組來作為數據包的存儲數據包*/
byte[] buffer = new byte[4096 * 5];
/**用來接收文件發送請求的字元串*/
String comm = null;
/**建立socekt通信,等待伺服器進行連接*/
try {
ss = new ServerSocket(4004);
s = ss.accept();
} catch (IOException e) {
e.printStackTrace();
}
/**讀取一行客戶端發送過來的約定信息*/
try {
InputStreamReader isr = new InputStreamReader(s.getInputStream());
BufferedReader br = new BufferedReader(isr);
comm = br.readLine();
} catch (IOException e) {
System.out.println("伺服器與客戶端斷開連接");
}
/**開始解析客戶端發送過來的請求命令*/
int index = comm.indexOf("/#");
/**判斷協議是否為發送文件的協議*/
String xieyi = comm.substring(0, index);
if(!xieyi.equals("111")){
System.out.println("伺服器收到的協議碼不正確");
return;
}
/**解析出文件的名字和大小*/
comm = comm.substring(index + 2);
index = comm.indexOf("/#");
String filename = comm.substring(0, index).trim();
String filesize = comm.substring(index + 2).trim();
/**創建空文件,用來進行接收文件*/
file = new File(filename);
if(!file.exists()){
try {
file.createNewFile();
} catch (IOException e) {
System.out.println("伺服器端創建文件失敗");
}
}else{
/**在此也可以詢問是否覆蓋*/
System.out.println("本路徑已存在相同文件,進行覆蓋");
}
/**【以上就是客戶端代碼中寫到的伺服器的准備部分】*/
/**
* 伺服器接收文件的關鍵代碼*/
try {
/**將文件包裝到文件輸出流對象中*/
fos = new FileOutputStream(file);
long file_size = Long.parseLong(filesize);
is = s.getInputStream();
/**size為每次接收數據包的長度*/
int size = 0;
/**count用來記錄已接收到文件的長度*/
long count = 0;
/**使用while循環接收數據包*/
while(count < file_size){
/**從輸入流中讀取一個數據包*/
size = is.read(buffer);
/**將剛剛讀取的數據包寫到本地文件中去*/
fos.write(buffer, 0, size);
fos.flush();
/**將已接收到文件的長度+size*/
count += size;
System.out.println("伺服器端接收到數據包,大小為" + size);
}
} catch (FileNotFoundException e) {
System.out.println("伺服器寫文件失敗");
} catch (IOException e) {
System.out.println("伺服器:客戶端斷開連接");
}finally{
/**
* 將打開的文件關閉
* 如有需要,也可以在此關閉socket連接
* */
try {
if(fos != null)
fos.close();
} catch (IOException e) {
e.printStackTrace();
}//catch (IOException e)
}//finally
}//public static void main(String[] args)
}//public class ServerReceive
客戶端源碼:
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.Socket;
/**
*
* 文件名:ClientSend.java
* 實現功能:作為客戶端向伺服器發送一個文件
*
* 具體實現過程:
* 1、建立與伺服器端的連接,IP:127.0.0.1, port:4004
* 2、將文件的名字和大小通過自定義的文件傳輸協議,發送到伺服器
* 3、循環讀取本地文件,將文件打包發送到數據輸出流中
* 4、關閉文件,結束傳輸
*
* */
public class ClientSend {
public static void main(String[] args) {
/**與伺服器建立連接的通信句柄*/
Socket s = null;
/**定義文件對象,即為要發送的文件
* 如果使用絕對路徑,不要忘記使用'/'和'\'的區別
* 具體區別,請讀者自行查詢
* */
File sendfile = new File("API.CHM");
/**定義文件輸入流,用來打開、讀取即將要發送的文件*/
FileInputStream fis = null;
/**定義byte數組來作為數據包的存儲數據包*/
byte[] buffer = new byte[4096 * 5];
/**定義輸出流,使用socket的outputStream對數據包進行輸出*/
OutputStream os = null;
/**檢查要發送的文件是否存在*/
if(!sendfile.exists()){
System.out.println("客戶端:要發送的文件不存在");
return;
}
/**與伺服器建立連接*/
try {
s = new Socket("127.0.0.1", 4004);
}catch (IOException e) {
System.out.println("未連接到伺服器");
}
/**用文件對象初始化fis對象
* 以便於可以提取出文件的大小
* */
try {
fis = new FileInputStream(sendfile);
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
/**首先先向伺服器發送關於文件的信息,以便於伺服器進行接收的相關准備工作
* 具體的准備工作,請查看伺服器代碼。
*
* 發送的內容包括:發送文件協議碼(此處為111)/#文件名(帶後綴名)/#文件大小
* */
try {
PrintStream ps = new PrintStream(s.getOutputStream());
ps.println("111/#" + sendfile.getName() + "/#" + fis.available());
ps.flush();
} catch (IOException e) {
System.out.println("伺服器連接中斷");
}
/**
* 此處睡眠2s,等待伺服器把相關的工作準備好
* 也是為了保證網路的延遲
* 讀者可自行選擇添加此代碼
* */
try {
Thread.sleep(2000);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
/**之前的准備工作結束之後
* 下面就是文件傳輸的關鍵代碼
* */
try {
/**獲取socket的OutputStream,以便向其中寫入數據包*/
os = s.getOutputStream();
/** size 用來記錄每次讀取文件的大小*/
int size = 0;
/**使用while循環讀取文件,直到文件讀取結束*/
while((size = fis.read(buffer)) != -1){
System.out.println("客戶端發送數據包,大小為" + size);
/**向輸出流中寫入剛剛讀到的數據包*/
os.write(buffer, 0, size);
/**刷新一下*/
os.flush();
}
} catch (FileNotFoundException e) {
System.out.println("客戶端讀取文件出錯");
} catch (IOException e) {
System.out.println("客戶端輸出文件出錯");
}finally{
/**
* 將打開的文件關閉
* 如有需要,也可以在此關閉socket連接
* */
try {
if(fis != null)
fis.close();
} catch (IOException e) {
System.out.println("客戶端文件關閉出錯");
}//catch (IOException e)
}//finally
}//public static void main(String[] args)
}//public class ClientSend
8、JAVA 把文件傳到伺服器.......
文件上傳到A以後 放到伺服器上面 然後他就有一個絕對的訪問路徑 也就是對應一個絕對的url 這樣就好辦了
Java提供了對URL訪問和大量的流操作的的API,可以很容易的完成對網路上資源的存取,下面的代碼段就完成了對一個網站的資源進行訪問:
......
destUrl="http://www.yourweb.com/java/Afile.zip";
//假設你把文件放到webroot底下的java文件裡面
url = new URL(destUrl);
httpUrl = (HttpURLConnection) url.openConnection();
//連接指定的網路資源
httpUrl.connect();
//獲取網路輸入流
bis = new BufferedInputStream(httpUrl.getInputStream());
......
得到流後下面你自己想怎麼操作就怎麼操作了
對於怎麼得到資源的連接地址這個方法很多 你可以專門提供一個Servlet 獲取到輸出的流後 Response.write轉門提供伺服器已上傳的文件 文件名可以一天位單位返回
客戶端用與上面同樣的方法得到文件名後 拆分 然後再繼續循環調用上面的方法 下載文件就ok了
呵呵 希望可以幫助到你
9、java有什麼文件伺服器
一般用apache,nginx
10、如何使用java跨伺服器讀取文件
如果倆個伺服器都在內網裡面,可以通過映射到本地磁碟,然後用Java直接讀取磁碟文件的方式進行讀取。如果不是,那麼你只能讓另一個伺服器以介面的方式提供文件讀取服務了。