java 客户端 基于http实现文件上传
原创
©著作权归作者所有:来自51CTO博客作者Dan淡淡的心的原创作品,请联系作者获取转载授权,否则将追究法律责任
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();
}
}