java 客戶端 基於http實現文件上傳

java Client 基於http實現文件上傳

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * 文件操作
 * @author 	luhua
 * @date	2019年7月29日
 */
public class FileOperation{

	public void main(String[] args) throws Exception{
		upLoad("http://localhost:8080/projectName/path","F:/a.mp3");
	}
	
	/**
	 * 文件上傳
	 * @param address 服務器http地址
	 * @param fileName 文件名
	 * @throws Exception
	 */
	public static void upLoad(String address,String fileName) throws Exception {
		if(null == address) throw new NullPointerException("address is null .");
		if(null == fileName) throw new NullPointerException("FileName is null.");
		upLoad(address, new File(fileName));
	}

	/**
	 * 文件上傳
	 * @param address 服務器http地址
	 * @param file	文件
	 * @throws Exception
	 */
	public static void upLoad(String address,File file) throws Exception {
		if(file == null) {
			throw new NullPointerException("File is null.");
		}else if(file.isDirectory()) {
			throw new Exception("File is directory .");
		}
		
		URL url=new URL(address);
		HttpURLConnection connection=(HttpURLConnection)url.openConnection();
		connection.setDoInput(true);
		connection.setDoOutput(true);
		connection.setRequestMethod("POST");
		connection.addRequestProperty("FileName", file.getName());
		connection.setRequestProperty("content-type", "text/html");
		BufferedOutputStream  out=new BufferedOutputStream(connection.getOutputStream());

		//讀取文件上傳到服務器
		FileInputStream fileInputStream=new FileInputStream(file);
		byte[]bytes=new byte[1024];
		int numReadByte=0;
		while((numReadByte=fileInputStream.read(bytes,0,1024))>0){
			out.write(bytes, 0, numReadByte);
		}
		out.flush();
		fileInputStream.close();
	}

}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章