近段要写一个接口,主要是手机端通过接口上传图片到服务器。
客户端测试代码如下:
服务器端,struts2的一个action方法
tomcat服务器一直启动着,然后客户端访问即可。
上边的都是测试代码,需要的话,只用改动下即可。
[color=red]注意的是,使用struts2接收文件的时候,客户端需要设置的content-type应该是text/html。因为struts2已经对此处理过了。[/color]
客户端测试代码如下:
public static void main(String[] args) {
String fileName = "c:/t_client.png";
String sUrl = "http://192.168.1.100:8080/lbs/recClientFile.action" ;
SendData sd = new SendData();
sd.sendFileToServer(fileName, sUrl);
}
public void sendFileToServer(String fileName,String sUrl){
File file = new File(fileName);
try {
URL url = new URL(sUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setUseCaches(false);
conn.setDoOutput(true);
conn.setDoInput(true);
// conn.setRequestProperty("Content-Type", "multipart/form-data"); 更改成下边的就行了
conn.setRequestProperty("Content-Type","text/html");
ByteArrayOutputStream bos = new ByteArrayOutputStream();
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
int len ;
while( (len = bis.read()) > -1 ){
bos.write(len);
}
byte fileData [] = bos.toByteArray();
DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
dos.write(fileData);
dos.flush();
dos.close();
bis.close();
bos.close();
conn.disconnect();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
服务器端,struts2的一个action方法
public String recClientFile(){
try {
InputStream is = request.getInputStream();
FileOutputStream fos = new FileOutputStream("c:/t_server.png");
int len ;
byte buffer [] = new byte[1024];
while( (len = is.read(buffer)) > -1 ){
fos.write(buffer, 0, len);
}
fos.close();
is.close();
System.err.println("rec the img from client over ! ");
} catch (IOException e) {
e.printStackTrace();
}
return null ;
}
tomcat服务器一直启动着,然后客户端访问即可。
上边的都是测试代码,需要的话,只用改动下即可。
[color=red]注意的是,使用struts2接收文件的时候,客户端需要设置的content-type应该是text/html。因为struts2已经对此处理过了。[/color]