今天调研了一下Java或Android下通过Http协议上传文件至服务器的实现方式,代码分为服务端和客户端,直接上代码
服务端JSP实现,将此jsp页面放在Tomcat下即可:
客户端:
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class HttpUpload {
private URL url;
private HttpURLConnection conn;
private File file;
public HttpUpload(){
file = new File("E:/she.mp3"); //要上传的本地文件
}
public void doPost(){
try {
/**上传的服务端接口,这里在模拟实现一个JSP页面来负责服务端处理*/
url = new URL("http://192.168.14.235:8000/upload.jsp");
conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod("POST");//通过POST方式
conn.setReadTimeout(5000);
conn.setConnectTimeout(10000);
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Charset", "UTF-8");
conn.setRequestProperty("Content-Type", "multipart/form-data"); //上传文件需要设置
FileInputStream fis = new FileInputStream(file);
OutputStream os = conn.getOutputStream();
byte[] buffer = new byte[2048];
int length = 0;
while((length = (fis.read(buffer))) != -1){
os.write(buffer, 0, length);
}
os.flush();
os.close();
if(conn.getResponseCode() != HttpURLConnection.HTTP_OK){
throw new RuntimeException("request url error!");
}
InputStream is = conn.getInputStream();
buffer = new byte[2048];
length = is.read(buffer);
System.out.println(new String(buffer, 0, length));
}
catch (MalformedURLException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
HttpUpload hu = new HttpUpload();
hu.doPost();
}
}
服务端JSP实现,将此jsp页面放在Tomcat下即可:
public void upload() {
try {
java.io.File file = new java.io.File(request.getRealPath("/"));
file = new java.io.File(request.getRealPath("/") + "/download.mp3");
if (!file.exists())
file.createNewFile();
java.io.FileOutputStream fos = new java.io.FileOutputStream(file);
byte[] bs = new byte[2048];
java.io.InputStream is = request.getInputStream();
int length = -1;
while ((length = is.read(bs)) != -1) {
fos.write(bs, 0, length);
}
fos.flush();
fos.close();
java.io.OutputStream os = response.getOutputStream();
os.write("upload completed!".getBytes());
}
catch (java.lang.Exception ex) {
}
}