核心功能为文件上传,将文件转换成字节流后,通过http协议,post到服务器上后,再转换成文件,达到文件上传到服务器的功能。没有使用Socket类去进行端口监听,一个是自己不会,一个服务器有防火墙端口都不放出来,不实用。
Ok,现在可以往服务器随便丢文件了,爽歪歪。
分为两部分,一部分为文件字节流发送部分,另一部分为服务器上文件字节流接受生成文件的部分。
核心代码:
/**
* 向指定URL发送POST方法的请求
*
* @param url 发送请求的URL
* @param fis 数据流。
* @param to 文件需要放置的路径
* @return URL所代表远程资源的响应
*/
public static String sendPost(String url, FileInputStream fis,String to) {
PrintWriter out = null;
BufferedReader in = null;
String result = "";
try {
URL realUrl = new URL(url);
// 打开和URL之间的连接
URLConnection conn = realUrl.openConnection();
conn.setRequestProperty("to", to);
//识别参数,为了是接受端可以一文件多用,方便配置
conn.setRequestProperty("method","upload");
// 发送POST请求必须设置如下两行
conn.setDoOutput(true);
conn.setDoInput(true);
byte[] bt=new byte[1024];
int has=0;
while((has=fis.read(bt))>0){
conn.getOutputStream().write(bt,0,has);
}
conn.getOutputStream().flush();
// 定义BufferedReader输入流来读取URL的响应
in = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += "\n" + line;
}
} catch (Exception e) {
System.out.println("发送POST请求出现异常!" + e);
e.printStackTrace();
}
// 使用finally块来关闭输出流、输入流
finally {
try {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
return result;
}
文件字节流接受部分,为了方便配置,就直接全部写到jsp中(放置到服务器上)
<%@ page language="java" contentType="text/html; charset=GBK" %>
<%@ page import="java.util.*,java.io.*" %>
<%
String method="";
//头部信息获取
method=request.getHeader("method");
if("".equals(method)||null==method){
method=request.getParameter("method");
}
//如果为文件上传
if(method.equals("upload")){
//获取字节流
ServletInputStream fis =request.getInputStream();
byte[] bt=new byte[1024];
int has=0;
//从头部获取路径 为啥要用header呢,测试发信request 的post字节流的数据只能读一次。那里已经放了文件的字节流了
//其他的东西我就只能放到头信息里了。
String way=request.getHeader("to");
if(way.equals("")){
out.print("{'result':'error'}");
return;
}
File file=new File(way);
//生成文件
FileOutputStream fos=new FileOutputStream(file);
while((has=fis.read(bt))>0){
fos.write(bt, 0, has);
}
fos.flush();
fos.close();
fis.close();
out.print("{'result':'success'}");
}
%>
Ok,现在可以往服务器随便丢文件了,爽歪歪。