使用http往服务端上传文件,要使用MultipartEntity,需要引入httpmime包,在附件中。
public static String postFile(String uploadFile, final String uploadType, String userId) throws ClientProtocolException, IOException, JSONException {
HttpClient httpclient = new DefaultHttpClient();
//设置通信协议版本
httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
Log.i("chopin", uploadFile);
HttpPost httppost = new HttpPost(Const.ImageUpload);
File file = new File(uploadFile);
MultipartEntity mpEntity = new MultipartEntity(); //文件传输
ContentBody cbFile = new FileBody(file);
mpEntity.addPart("file", cbFile);
mpEntity.addPart("userId",new StringBody(userId));
mpEntity.addPart("uploadType",new StringBody(uploadType));
httppost.setEntity(mpEntity);
System.out.println("executing request " + httppost.getRequestLine());
HttpResponse response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();
System.out.println(response.getStatusLine());//通信Ok
String json="";
String path="";
if (resEntity != null) {
json=EntityUtils.toString(resEntity,"utf-8");
Log.i("chopin", json);
JSONObject p=null;
try{
p=new JSONObject(json);
path=(String) p.get("path");
}catch(Exception e){
e.printStackTrace();
}
}
if (resEntity != null) {
resEntity.consumeContent();
}
httpclient.getConnectionManager().shutdown();
return path;
}
分享到:
相关推荐
java上传文件到服务器,将本地的文件上传到服务器上去
使用Java远程上传压缩包到服务器,或者在服务器上拉去压缩包或者文件,在服务器上创建目录。
java上传文件到linux服务器,操作linux服务器上文件,下载linux服务器文件,删除linux服务器文件。ganymed-ssh2远程操作服务器文件
java实现上传文件到远程服务器(spring mvc)
这是我使用java实现的linux和ftp服务器文件上传下载工具,需要电脑安装jdk8, 启动命令,java -jar linuxAndFtp.jar 启动成功后,浏览器访问:http://localhost:9999 服务器的账号密码通过服务器列表页面管理,添加的...
java分布式项目中,运用ftp客户端实现图片上传,nginx提供http服务实现图片回显
本测试服务主要是利用postman上传,后端接收图片保存至服务器,并且返回一个可以下载图片的URL路径
JAVA通过SMB的方式下载、上传远程Linux服务器的文件
该项目是简单介绍程序调用FTP上传和下载文件到服务器的方法。
(1)分别运行工程两个包中的两个.java文件(UploadClient.java和UploadServer.java)分别会弹出“上传客服端”和“上传服务器”两个窗口。 (2)单击“上传服务器”窗口中的“启动服务..”按钮。 (3)单击“上传...
java上传文件到ftp服务器,从ftp服务器下载东西demo,日管理
JAVA中生成xml文件到指定路径和上传到ftp服务器到指定路径的方法。
Java FTP 实现跨服务器文件上传下载
服务器上传文件到ownCloud私有云,java调用curl上传,代码简单