我在将文件上传到服务器时遇到一些困难,我需要知道使用namevaluepair上传文件的完整代码。听到我的android代码,我只获取我的文件路径,如何将其上传到服务器,引用为“nameValuePairs.add(new BasicNameValuePair(”attachment“,selectedFilePath));”
String selectedFilePath="downloads/harry.txt" //(My file Path)
InputStream is = null;
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("postiontitle", positiontitle));
nameValuePairs.add(new BasicNameValuePair("description", description));
nameValuePairs.add(new BasicNameValuePair("jobtype", jobtype));
nameValuePairs.add(new BasicNameValuePair("visatype", visatype));
if (selectedFilePath != null)
{
nameValuePairs.add(new BasicNameValuePair("attachment", selectedFilePath));
}
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://10.0.3.2/dfsdsd/postjob");
// HttpPost httpPost = new
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
int code = response.getStatusLine().getStatusCode();
String rescode = String.valueOf(code);
//result=is.toString();
return rescode;
} catch (MalformedURLException e) {
return "No Internet";
} catch (IOException e) {
return "No Internet";
}
}
答案 0 :(得分:0)
如果你想简单快速,那么我会建议你ION Library
发布multipart / form-data并使用上传进度条读取JSON使用ION:
Ion.with(getContext())
.load("https://koush.clockworkmod.com/test/echo")
.uploadProgressBar(uploadProgressBar)
.setMultipartParameter("goop", "noop")
.setMultipartFile("archive", "application/zip", new File("/sdcard/filename.zip"))
.asJsonObject()
.setCallback(...)
答案 1 :(得分:0)
使用Retrofil或Okhttp。
//