JAVA通訊(1)-- 使用Socket實現檔案上傳與下載
客戶端
/**
* 檔案上傳客戶端
*
* @author chen.lin
*
*/
public class UploadClient extends JFrame {
/**
*
*/
private static final long serialVersionUID = -8243692833693773812L;
private String ip;// 伺服器ip
private int port;// 埠
private Properties prop;
private List<FileBean> fileBeans = new ArrayList<FileBean>();// 從file.xml讀到的檔案集合
private Socket socket; // 客戶端socket
private ByteArrayInputStream bais;
private SequenceInputStream sis;
private BufferedOutputStream bos;
private InputStream fs;
public UploadClient() {
// 初始化資料
initDatas();
// 開始上傳檔案
startUploadFile();
// 設定視窗屬性
initViews();
}
private void initViews() {
setTitle("上傳客戶端");
getContentPane().setLayout(null);
setBounds(160, 200, 440, 300);
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
setVisible(true);
}
/**
* 開始上傳檔案....
*/
public void startUploadFile() {
try {
socket = new Socket(ip, port);
if (!socket.isClosed() && socket.isConnected()) {
Logger.log("客戶端連線成功....");
System.out.println("客戶端連線成功....");
} else {
Logger.log("連線失敗, 請與開發人員聯絡....");
JOptionPane.showMessageDialog(null, "連線失敗, 請與開發人員聯絡");
return;
}
for (FileBean fileBean : fileBeans) {
String filePath = fileBean.getPath();
Logger.log("filepath===" + filePath);
File file = null;
if (filePath != null && !"".equals(filePath.trim())) {
int indexOf = filePath.lastIndexOf("/");
String fileName = filePath.substring(indexOf + 1);
if (filePath.startsWith("http://")) {
URL url = new URL(filePath);
file = new File(filePath);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(5000);
conn.setRequestMethod("GET");
conn.setConnectTimeout(5000);
if (conn.getResponseCode() == 200) {
fs = conn.getInputStream();
}else {
Logger.log("錯誤資訊:檔案網路路徑錯誤:" + filePath);
}
}else {
file = new File(fileBean.getPath());
fs = new FileInputStream(file);
}
Logger.log("filename=" + fileName);
long fileSize = file.length();
Logger.log("filesize===" + fileSize);
if (fileSize / 1024 / 1024 > 70) {
Logger.log("檔案超過了70M,不能上傳");
return;
}
//定義一個256位元組的區域來儲存檔案資訊。
byte[] b = fileName.getBytes();
byte[] info = Arrays.copyOf(b, 256);
bais = new ByteArrayInputStream(info);
sis = new SequenceInputStream(bais, fs);
if (socket.isClosed()) {
Logger.log("重新連線成功!");
System.out.println("重新連線成功!");
socket = new Socket(ip, port);
}
bos = new BufferedOutputStream(socket.getOutputStream());
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
byte[] buf = new byte[1024];
int len = 0;
while ((len = sis.read(buf)) != -1) {
bos.write(buf, 0, len);
bos.flush();
}
//關閉
socket.shutdownOutput();
String result = br.readLine();
Logger.log(fileBean.getName() + "上傳:" + result);
if ("success".equals(result.trim())) {
fileBean.setState(1);
XmlUtil.changeFileState(prop.getProperty("xmlPath"), fileBean);
}
br.close();
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (bos != null) {
bos.close();
}
if (sis != null) {
sis.close();
}
if (fs != null) {
fs.close();
}
if (bais != null) {
bais.close();
}
if (socket != null) {
socket.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 初始化資料
*
* @throws UnknownHostException
* @throws Exception
*/
private void initDatas() {
try {
prop = PropUtil.getProp();
ip = prop.getProperty("ip");
if (ip.startsWith("http://")) {
ip = InetAddress.getByName(ip).getHostAddress();
}
port = Integer.parseInt(prop.getProperty("port"));
final String xmlPath = prop.getProperty("xmlPath");
Logger.log("xmlPath===" + xmlPath);
System.out.println("xmlPath===" + xmlPath);
// 因為讀的是遠端xml,比較耗時,所以放線上程裡執行
ExecutorService executorService = Executors.newCachedThreadPool();
ArrayList<Future<List<FileBean>>> list = new ArrayList<Future<List<FileBean>>>();
list.add(executorService.submit(new CallThread(xmlPath)));
for (Future<List<FileBean>> fs : list) {
List<FileBean> fileBean = fs.get();
fileBeans.addAll(fileBean);
}
} catch (Exception e) {
e.printStackTrace();
Logger.log("error:" + e.getMessage());
//JOptionPane.showMessageDialog(null, "error:" + e.getMessage());
}
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
new UploadClient();
System.exit(0);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}
伺服器端程式碼
/**
* 檔案上傳伺服器端
*
* @author chen.lin
*
*/
public class UploadServer extends JFrame {
/**
*
*/
private static final long serialVersionUID = -5622620756755192667L;
private JTextField port;
private ServerSocket server;
private volatile boolean isRun = false;
private ExecutorService pool = Executors.newFixedThreadPool(10);
public UploadServer() {
setTitle("上傳伺服器");
getContentPane().setLayout(null);
JLabel label = new JLabel("監聽視窗:");
label.setBounds(86, 80, 74, 15);
getContentPane().add(label);
port = new JTextField("9000");
port.setBounds(178, 77, 112, 21);
getContentPane().add(port);
port.setColumns(10);
/**
* 啟動服務
*/
final JButton btnStart = new JButton("啟動伺服器");
btnStart.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
port.setEnabled(false); // 控制元件黑白不可變
btnStart.setEnabled(false);
isRun = true;
new Thread(new Runnable() {
@Override
public void run() {
try {
server = new ServerSocket(Integer.parseInt(port.getText()));
System.out.println("伺服器開始啟動了........");
while (isRun) {
pool.execute(new UploadThread(server.accept()));
};
} catch (NumberFormatException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
pool.shutdown();
}
}
}).start();
}
});
btnStart.setBounds(73, 145, 93, 23);
getContentPane().add(btnStart);
JButton btnStop = new JButton("停止伺服器");
btnStop.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
port.setEnabled(true);
btnStart.setEnabled(true);
isRun = false;
server = null;
}
});
btnStop.setBounds(209, 145, 93, 23);
getContentPane().add(btnStop);
setBounds(600, 200, 380, 300);
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
new UploadServer();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* 進行檔案傳輸耗記憶體,所以必須放線上程中執行
*/
class UploadThread implements Runnable {
private Socket socket;
private SimpleDateFormat sdf;
private BufferedInputStream bis;
private BufferedOutputStream bos;
UploadThread(Socket socket) {
this.socket = socket;
sdf = new SimpleDateFormat("yyyyMMddHH");
}
@Override
public void run() {
try {
bis = new BufferedInputStream(socket.getInputStream());
byte[] info = new byte[256];
bis.read(info);
String fileName = new String(info).trim();
String filePath = PropUtil.getProp().getProperty("filePath");
String fullPath = filePath + "/" + sdf.format(new Date());
File dirs = new File(fullPath);
if (!dirs.exists()) {
dirs.mkdirs();
}
PrintWriter pw = new PrintWriter(socket.getOutputStream(),true);
if (!TextUtil.isEmpty(fileName)) {
bos = new BufferedOutputStream(new FileOutputStream(fullPath + "/" + fileName));
byte[] buf = new byte[1024];
int len = 0;
while ((len = bis.read(buf)) != -1) {
bos.write(buf, 0, len);
bos.flush();
}
System.out.println(fileName + " 檔案傳輸成功");
pw.println("success");
}else {
pw.println("failure");
}
pw.close();
} catch (IOException e) {
e.printStackTrace();
} finally{
try {
if (bos != null) {
bos.close();
}
if (bis != null) {
bis.close();
}
if (socket != null) {
socket.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
相關的工具類
/**
* 記錄日誌資訊
* @author chen.lin
*
*/
public class Logger {
public static void log(String name){
try {
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHH");
String path = "d:/upload_log/" + sdf.format(new Date()) ;
File file = new File(path);
if (!file.exists()) {
file.mkdirs();
}
FileOutputStream out = new FileOutputStream(new File(path + "/log.txt"), true);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(out));
bw.write(name + "\r\n");
bw.flush();
bw.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 讀取配置檔案工具
* @author chen.lin
*
*/
public class PropUtil {
private static Properties prop;
static{
prop = new Properties();
//InputStream inStream = PropUtil.class.getClassLoader().getResourceAsStream("d:/files/config.properties");
try {
InputStream inStream = new FileInputStream(new File("d:/files/config.properties"));
prop.load(inStream);
} catch (IOException e) {
e.printStackTrace();
}
}
public static Properties getProp(){
return prop;
}
public static void main(String[] args) {
String xmlPath = (String) PropUtil.getProp().get("filePath");
System.out.println(xmlPath);
}
}
/**
* 文字工具
* @author chen.lin
*
*/
public class TextUtil {
public static boolean isEmpty(String text){
if (text == null || "".equals(text.trim())) {
return true;
}
return false;
}
}
/**
* xml檔案解析與生成
*
* @author chen.lin
*
*/
public class XmlUtil {
/**
* 從xml檔案中獲取檔案資訊
*
* @param xmlPath
* @return
* @throws Exception
*/
public static List<FileBean> getFileBeanFromXml(String xmlPath) throws Exception {
List<FileBean> list = null;
if (TextUtil.isEmpty(xmlPath)) {
return null;
}
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
XmlPullParser parser = factory.newPullParser();
InputStream inputStream = null;
if (xmlPath.startsWith("http://")) {
URL url = new URL(xmlPath);
inputStream = url.openStream();
} else {
inputStream = new FileInputStream(new File(xmlPath));
}
parser.setInput(inputStream, "UTF-8");
int eventType = parser.getEventType();
FileBean bean = null;
while (eventType != XmlPullParser.END_DOCUMENT) {
switch (eventType) {
case XmlPullParser.START_DOCUMENT:
list = new ArrayList<FileBean>();
break;
case XmlPullParser.START_TAG:
if ("file".equals(parser.getName())) {
bean = new FileBean();
bean.setId(parser.getAttributeValue(0));
} else if ("name".equals(parser.getName())) {
bean.setName(parser.nextText());
} else if ("path".equals(parser.getName())) {
bean.setPath(parser.nextText());
} else if ("state".equals(parser.getName())) {
int state = Integer.parseInt(parser.nextText());
bean.setState(state);
}
break;
case XmlPullParser.END_TAG:
// 新增物件到list中
if ("file".equals(parser.getName()) && bean != null && bean.getState() == 0) {
list.add(bean);
bean = null;
}
break;
}
// 當前解析位置結束,指向下一個位置
eventType = parser.next();
}
return list;
}
/**
* 修改xml內容
*
* @param xmlPath
* @param bean
*/
public static void changeFileState(String xmlPath, FileBean bean) {
try {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = null;
if (xmlPath.startsWith("http://")) {
URL url = new URL(xmlPath);
doc = db.parse(url.openStream());
} else {
doc = db.parse(new File(xmlPath));
}
NodeList list = doc.getElementsByTagName("file");// 根據標籤名訪問節點
for (int i = 0; i < list.getLength(); i++) {// 遍歷每一個節點
Element element = (Element) list.item(i);
String id = element.getAttribute("id");
if (id.equals(bean.getId())) {
element.getElementsByTagName("state").item(0).getFirstChild().setNodeValue(bean.getState()+"");
}
}
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource domSource = new DOMSource(doc);
// 設定編碼型別
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
StreamResult result = new StreamResult(new FileOutputStream(xmlPath));
transformer.transform(domSource, result);
} catch (Exception ex) {
ex.printStackTrace();
}
}
/**
* 生成新的xml檔案
*
* @param xmlPaht
*/
public static void createFileXml(String xmlPath, FileBean bean) throws Exception {
XmlSerializer seria = XmlPullParserFactory.newInstance().newSerializer();
OutputStream out = null;
if (xmlPath.startsWith("http://")) {
URL url = new URL(xmlPath);
URLConnection conn = url.openConnection();
out = conn.getOutputStream();
} else {
out = new FileOutputStream(new File(xmlPath));
}
seria.setOutput(out, "UTF-8"); // 設定輸出方式,這裡使用OutputStream,編碼使用UTF-8
seria.startDocument("UTF-8", true); // 開始生成xml的檔案頭
seria.startTag(null, "files");
seria.startTag(null, "file");
seria.attribute(null, "id", bean.getId().toString()); // 新增屬性,名稱為id
seria.startTag(null, "name");
seria.text(bean.getName().toString()); // 新增文字元素
seria.endTag(null, "name");
seria.startTag(null, "path");
seria.text(String.valueOf(bean.getPath()));// 這句話應該可以用來
seria.endTag(null, "path");
seria.startTag(null, "state");
seria.text(bean.getState() + "");
seria.endTag(null, "state");
seria.endTag(null, "file");
seria.endTag(null, "files"); // 標籤都是成對的
seria.endDocument();
out.flush();
out.close(); // 關閉輸出流
}
public static void main(String[] args) throws Exception {
String xmlPath = PropUtil.getProp().getProperty("xmlPath");
FileBean bean = new FileBean();
bean.setId("1");
bean.setState(1);
XmlUtil.changeFileState(xmlPath, bean);
/*
* List<FileBean> list = XmlUtil.getFileBeanFromXml(xmlPath); for (FileBean bean : list) { System.out.println(bean.getName()); }
*/
}
}
實體類
/**
* 檔案bean
*
* @author chenlin
*
*/
public class FileBean {
private String id; //id
private String name;//檔名稱
private String path;//檔案路徑
private int state;//上傳結果0未上傳,1已經上傳,2上傳錯誤
public FileBean() {
}
public FileBean(String id, int state) {
this.id = id;
this.state = state;
}
public FileBean(String id, String name, String path, int state) {
this.id = id;
this.name = name;
this.path = path;
this.state = state;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
public int getState() {
return state;
}
public void setState(int state) {
this.state = state;
}
@Override
public String toString() {
return "FileBean [id=" + id + ", name=" + name + ", path=" + path + ", state=" + state + "]";
}
}
回撥函式
class CallThread implements Callable<List<FileBean>> {
private String xmlPath;
public CallThread(String xmlPath) {
this.xmlPath = xmlPath;
}
@Override
public List<FileBean> call() throws Exception {
return XmlUtil.getFileBeanFromXml(xmlPath);
}
}
———————————————————————
(java 架構師全套教程,共760G, 讓你從零到架構師,每月輕鬆拿3萬)
有需求者請進站檢視,非誠勿擾
https://item.taobao.com/item.htm?spm=686.1000925.0.0.4a155084hc8wek&id=555888526201
01.高階架構師四十二個階段高
02.Java高階系統培訓架構課程148課時
03.Java高階網際網路架構師課程
04.Java網際網路架構Netty、Nio、Mina等-視訊教程
05.Java高階架構設計2016整理-視訊教程
06.架構師基礎、高階片
07.Java架構師必修linux運維繫列課程
08.Java高階系統培訓架構課程116課時
(送:hadoop系列教程,java設計模式與資料結構, Spring Cloud微服務, SpringBoot入門)
——————————————————————–
相關推薦
JAVA通訊(1)-- 使用Socket實現檔案上傳與下載
客戶端 /** * 檔案上傳客戶端 * * @author chen.lin * */ public class UploadClient extends JFrame { /** * */ priva
java實現檔案上傳與下載
東風化宇,檔案上傳 一、對於檔案上傳,瀏覽器在上傳的過程中是將檔案以流的形式提交到伺服器端的,Servlet獲取上傳檔案的輸入流然後再解析裡面的請求引數是比較麻煩。 JSP程式碼,POST請求,表單必須設定為enctype="multipar
struts2實現檔案上傳與下載功能
一、Demo介紹 基於struts2框架,實現多檔案的上傳和下載功能。 實現原理圖: 部分介面圖: 上傳成功及下載頁面: 二、主要程式碼 uploadFile.jsp:在form表單中包含一個文字框(上傳使用者的姓名)和兩個檔案上傳選項. <%@
Http伺服器實現檔案上傳與下載(二)
一、引言 歡迎大家接著看我的部落格,如何大家有什麼想法的話回覆我哦,閒話不多聊了,接著上一講的內容來說吧,在上一節中已經講到了請求頭字串的解析,並且在解析中我我們已經獲取了url。就是上節中提到的/doing。當瀏覽器傳送了/doing請求後,這是的與伺服器的連線並沒有
Http伺服器實現檔案上傳與下載(五)
一、引言 歡迎大家和我一起編寫Http伺服器實現檔案的上傳和下載,現在我回顧一下在上一章節中提到的一些內容,之前我已經提到過檔案的下載,在檔案的下載中也提到了檔案的續下載只需要在響應頭中填寫Content-Range這一欄位,並且伺服器的檔案指標指向讀取的指定
Http伺服器實現檔案上傳與下載(一)
一、引言 大家都知道web程式設計的協議就是http協議,稱為超文字傳輸協議。在J2EE中我們可以很快的實現一個Web工程,但在C++中就不是非常的迅速,原因無非就是底層的socket網路編寫需要自己完成,上層的http協議需要我們自己完成,使用者介面需要我們自己完
Http伺服器實現檔案上傳與下載(三)
一、引言 在前2章的內容基本上已經講解了整個的大致流程。在設計Http伺服器時,我設計為四層的結構,最底層是網路傳輸層,就是socket程式設計。接著一層是請求和響應層,叫做Request和Response。在上一層是URL解析流程走向層。最頂層我設計為索引層。這一層主要多檔案時對檔案進行記憶體上的索引
Http伺服器實現檔案上傳與下載(四)
一、引言 歡迎大家來到和我一起編寫Http伺服器實現檔案的上傳和下載,現在我稍微回顧一下之前我說的,第一、二章說明說明了整體的HTTP走向,第三章實現底層的網路程式設計。接著這一章我想給大家講的是請求獲取,和響應傳送的內容。這裡主要講解的響應內容,為什麼?因為我們編寫的是一個與瀏覽器互動的HTTP伺服器
使用jsp/servlet簡單實現檔案上傳與下載
public class UploadServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException,
Spring 實現檔案上傳與下載
檔案上傳 upload.jsp: <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ include file="
struts2實現檔案上傳與下載
一、單檔案上傳 1、檔案上傳條件: (1)請求方法必須是post (2)enctype的屬性值必須為multipart/form-data (3)提供一個檔案選擇域 2、檔案上傳jsp程式碼 <%@ page language="java" c
Java Springboot結合FastDFS實現檔案上傳以及根據圖片url將圖片上傳至圖片伺服器
上一篇文章我們已經講解了如何搭建FastDFS圖片伺服器,環境我們準備好了現在就讓我們開始與Java結合將他應用到實際的專案中吧。本篇文章我們將會展示上傳圖片到FastDFS圖片伺服器以及通過外網的圖片url將圖片上傳至我們自己的圖片伺服器中。 1.建立springbo
Java實現檔案上傳和下載
上面的博文我寫了Java對檔案操作的功能https://blog.csdn.net/qq_24380635/article/details/83273359,這次記錄一下檔案上傳和下載的功能。看看兩者有什麼不同,就可以知道檔案操作和檔案上傳下載有什麼不同了。我也是一點點懂,也
Java基於TCP協議的Socket客戶端檔案上傳與下載
import java.io.BufferedInputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.File; import java.io.F
Java中利用MultipartFile實現檔案上傳
JavaWeb專案頁面實現檔案上傳功能 jsp檔案增加檔案上傳控制元件,可以放在form表單內,增加隱藏域儲存上傳路徑提交到後臺。 <div class="form-group"> <div class="col-sm-7 center "&g
用socket自定義簡單協議實現檔案上傳與接受
一個上傳的資料包,主要包含檔案頭和檔案內容倆部分,主要按下面的格式,傳送: "File-Name:xxxxxx.zip;File-Type:exe;File-Length:1029292\r\n" ------檔案內容--------- 1、服務端的檔案接受服務 MySoc
如何在基於Java的Web專案中實現檔案上傳和下載?
在Sevlet 3 以前,Servlet API中沒有支援上傳功能的API,因此要實現上傳功能需要引入第三方工具從POST請求中獲得上傳的附件或者通過自行處理輸入流來獲得上傳的檔案,我們推薦使用Apac
java web 一行程式碼實現檔案上傳下載
每當要實現檔案上傳下載的功能時,都要複製貼上拼湊程式碼。如果用了不同的框架,程式碼還不一樣,配置啥的一堆,甚是繁瑣,不喜歡。科學家們喜歡把紛繁複雜的自然現象總結為一個個簡潔的公式,我們也來試試,把上傳下載整成一行程式碼~ 花了一天時間,整了個通用
java web檔案上傳與下載
jsp程式碼(檔案上傳) <form id="upLoad" method="post">
關於myeclipse實現檔案上傳與使用的路徑問題
在檔案上傳的時候編寫檔案儲存應該儲存到 myeclipse 的workspace的工程目錄下面,而不是放到tomcat的webapps下面。否則eclipse 無法更新檔案。 換句話講,在eclipse中新增檔案,comcat的專案檔案中可以看見新增的文體,但是反過來,在comcat的工程目錄下