参考博文:
http://blog.csdn.net/thinkpadshi/article/details/8173765
http://blog.csdn.net/helloworlddream/article/details/9469497
今天下午搞了一下Webservice实现文件上传的功能,接下来的项目中要使用,下面是今天的劳动成果。主要记录一下Webservice服务端怎么写,Android客户端怎么调用,至于form表单的提交,我看了一下上面的提到的博文,应该也是满足的,代码基本借鉴上面的两篇博文中的代码,惭愧,但是还是记录一下,方便自己以后使用,加深一下印象。
完整Service代码:
import java.io.FileOutputStream; import java.io.InputStream; import java.io.OutputStream; import java.util.Calendar; import javax.activation.DataHandler; import org.springframework.stereotype.Service; @Service public class MaeipServiceJws { // 使用DataHandler类型参数上传文件 public boolean uploadWithDataHandler(DataHandler profile_picture) { FileOutputStream fos = null; try { profile_picture.getContentType(); profile_picture.getContent(); String[] fileinfo=profile_picture.getName().split("\\."); if (fileinfo.length>1) { fos = new FileOutputStream("D:\\WebserviceUpload\\"+Calendar.getInstance().getTimeInMillis()+"."+fileinfo[1]); }else { fos = new FileOutputStream("D:\\WebserviceUpload\\"+Calendar.getInstance().getTimeInMillis()); } // 可通过DataHandler类的getInputStream方法读取上传数据 writeInputStreamToFile(profile_picture.getInputStream(), fos); fos.close(); } catch (Exception e) { return false; } finally { if (fos != null) { try { fos.close(); } catch (Exception e) { } } } return true; } private void writeInputStreamToFile(InputStream is, OutputStream os) throws Exception { int n = 0; byte[] buffer = new byte[8192]; while ((n = is.read(buffer)) > 0) { os.write(buffer, 0, n); } } }
private void uploadImageTest() { File file = new File("/storage/sdcard0/xixi.png"); String uploadUrl="http://192.168.1.111:8082/maeip/services/MaeipServiceJws/uploadWithDataHandler"; RequestParams params=new RequestParams(); System.out.println(file.length()); try { params.put("profile_picture", file); AsyncHttpClient client =new AsyncHttpClient(); //实例话对象 client.setTimeout(600000); //设置链接超时,如果不设置,默认为10s client.post(uploadUrl,params,uploadResponseHander()); } catch (Exception e) { e.printStackTrace(); } } /** * 上传回调 * @return */ private AsyncHttpResponseHandler uploadResponseHander() { return new AsyncHttpResponseHandler() { @Override public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) { Log.i("UploadResult", "上传完成"); } @Override public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) { error.printStackTrace(); Log.i("UploadResult", "上传完成"); } }; }