[英]How to upload multiple selected files (i.e..doc,pdf,jpeg,png) in server at android
[英]How to upload .pdf .doc .txt files to server(mysql database) using Android
將文件上傳到服務器時遇到一些困難,我需要知道使用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";
}
}
如果您想簡單快速地我會建議您ION Library
發布多部分/表單數據並使用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);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.