当前位置 : 主页 > 编程语言 > java >

java 传送文件

来源:互联网 收集:自由互联 发布时间:2022-07-20
tomcat注意要把这个配置 client端核心代码: public static boolean post2(String url) { File file = new File("D:/psu.jpg"); InputStream in = null; String responseContent = null; try { in = new FileInputStream(file); } catch (FileN


tomcat注意要把这个配置

java 传送文件_java

 

client端核心代码:

 

public static boolean post2(String url) {
File file = new File("D:/psu.jpg");
InputStream in = null;
String responseContent = null;
try {
in = new FileInputStream(file);
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} try {
if (url == null || url.trim().equals("")) { throw new Exception("目标url地址无效");
}
URL url2 = new URL(url);
HttpURLConnection hc = (HttpURLConnection) url2.openConnection();
hc.setRequestMethod("POST"); System.setProperty("sun.net.client.defaultConnectTimeout",
String.valueOf(HttpTest.connectTimeOut));// (单位:毫秒)jdk1.4换成这个,连接超时
System.setProperty("sun.net.client.defaultReadTimeout",
String.valueOf(HttpTest.readTimeOut)); hc.setDoOutput(true);
OutputStream os = hc.getOutputStream();
// hc.getInputStream();
byte[] tempbytes = new byte[100];
int byteread = 0;
while ((byteread = in.read(tempbytes)) != -1) {
os.write(tempbytes, 0, byteread); System.out.println(byteread);
}
os.flush();
os.close();//严重注意,只有有了客户端的这部分的 读 的代码,才会有 写 的过程
BufferedReader rd = new BufferedReader(new InputStreamReader(input,
"GBK"));
String tempLine = rd.readLine();
StringBuffer tempStr = new StringBuffer();
String crlf = System.getProperty("line.separator");
while (tempLine != null) {
tempStr.append(tempLine);
tempStr.append(crlf);
tempLine = rd.readLine();
}
responseContent = tempStr.toString();
rd.close();
input.close(); hc.disconnect();
} catch (Exception e) {
e.printStackTrace();
return false; }
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
} return true;
}


server端核心代码

protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException { String fileName = "D:/copy.jpg";
RandomAccessFile file = null;
ServletInputStream sis = null; try {
file = new RandomAccessFile(fileName, "rw"); sis = request.getInputStream();
byte[] buf = new byte[1024];
int len = sis.read(buf);
while (len != -1) {
System.out.println(len);
file.write(buf, 0, len);
len = sis.read(buf);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (file != null)
file.close(); }
if (sis != null)
sis.close();
}
上一篇:java 线程池应用小例子
下一篇:没有了
网友评论