1、服务器jsp页面upload.jsp
<%@page import="java.io.FileWriter"%>
<%@page import="java.io.File"%>
<%@page import="java.util.Date"%>
<%@page import="java.text.SimpleDateFormat"%>
<%@page import="java.io.IOException"%>
<%@page import="java.io.InputStreamReader"%>
<%@page import="java.io.FileReader"%>
<%@page import="java.io.BufferedWriter"%>
<%@page import="java.io.BufferedReader"%>
<%@page import="java.io.InputStream"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
request.setCharacterEncoding("UTF-8");
String savePath = "../log/";
BufferedReader reader = null;
BufferedWriter writer = null;
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
String fileName = sdf.format(new Date()) + ".log";
File file = null;
StringBuffer buffer = new StringBuffer();
String temp = null;
try {
reader = new BufferedReader(new InputStreamReader(request.getInputStream()));
file = new File(savePath + fileName);
if(!file.exists()){
file.createNewFile();
}
writer = new BufferedWriter(new FileWriter(file));
while((temp = reader.readLine()) != null){
buffer.append(temp);
}
writer.write(buffer.toString());
out.print("upload Success");
} catch (Exception e) {
e.printStackTrace();
out.print("upload server Exception");
}finally{
try{
if(reader != null){
reader.close();
}
if(writer != null){
writer.close();
}
}catch(IOException e){}
}
%>
2、上传文本文件方法
public static void uploadFile(String uploadFile)
{
String filePath = "/mnt/sdcard/"+ uploadFile;
try
{
URL url = new URL("https://www.geekapp.cn/upload.jsp");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
/* 允许Input、Output,不使用Cache */
con.setDoInput(true);
con.setDoOutput(true);
con.setUseCaches(false);
/* 设定传送的method=POST */
con.setRequestMethod("POST");
/* setRequestProperty */
con.setRequestProperty("Connection", "Keep-Alive");
con.setRequestProperty("Charset", "UTF-8");
con.setRequestProperty("Content-Type",
"multipart/form-data" );
/* 设定DataOutputStream */
DataOutputStream ds = new DataOutputStream(con.getOutputStream());
/* 取得文件的FileInputStream */
FileInputStream fStream = new FileInputStream(filePath);
/* 设定每次写入1024bytes */
byte[] buffer = new byte[1024];
int length = -1;
/* 从文件读取数据到缓冲区 */
while ((length = fStream.read(buffer)) != -1)
{
/* 将数据写入DataOutputStream中 */
ds.write(buffer, 0, length);
}
fStream.close();
ds.flush();
ds.close();
} catch (Exception e)
{
Log.e("文件上传", e.getMessage());
}
}
原创内容转载请保留出处GEEK笔记(https://www.geekapp.cn/)。