如何使用Android将.pdf.doc.txt文件上载到服务器(mysql数据库)
我在上传文件到服务器时遇到了一些困难,我需要知道使用namevaluepair上传文件的完整代码。Hear是我的android代码,我只获取我的文件路径,如何将其上传到服务器,引用为nameValuePairs.addnew BasicNameValuePairattachment,selectedFilePath如何使用Android将.pdf.doc.txt文件上载到服务器(mysql数据库),android,arrays,android-asynctask,Android,Arrays,Android Asynctask,我在上传文件到服务器时遇到了一些困难,我需要知道使用namevaluepair上传文件的完整代码。Hear是我的android代码,我只获取我的文件路径,如何将其上传到服务器,引用为nameValuePairs.addnew BasicNameValuePairattachment,selectedFilePath String selectedFilePath="downloads/harry.txt" //(My file Path) InputStre
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";
}
}
如果你想要简单和快速,那么我会建议你 发布多部分/表单数据并使用带有ION的上载进度条读取JSON:
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(...)
使用Retrofil或Okhttp
public static final String MULTIPART_FORM_DATA = "multipart/form-data";
@NonNull
private RequestBody createPartFromString(String descriptionString) {
return RequestBody.create(
MediaType.parse(MULTIPART_FORM_DATA), descriptionString);
}
@NonNull
private MultipartBody.Part prepareFilePart(String partName, Uri fileUri) {
// https://github.com/iPaulPro/aFileChooser/blob/master/aFileChooser/src/com/ipaulpro/afilechooser/utils/FileUtils.java
// use the FileUtils to get the actual file by uri
File file = FileUtils.getFile(this, fileUri);
// create RequestBody instance from file
RequestBody requestFile =
RequestBody.create(MediaType.parse(MULTIPART_FORM_DATA), file);
// MultipartBody.Part is used to send also the actual file name
return MultipartBody.Part.createFormData(partName, file.getName(), requestFile);
}
你为什么不使用这个库呢,它简单、快速、高效,并且可以在后台工作多部分不回答我需要知道使用namevaluepair上传文件的完整代码。我建议你不要使用namevaluepair,因为它是包org.apache的一部分,该包被Android 22弃用,被Android MOk删除。然后以不同的方式以键值对发送文件。这仍然不是多部分的。