客户端通过http协议上传文件,struts2服务端接受

近段要写一个接口,主要是手机端通过接口上传图片到服务器。
客户端测试代码如下:


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]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值