在android中上传文件和其他字符串参数

别裁伪体亲风雅,转益多师是汝师。这篇文章主要讲述在android中上传文件和其他字符串参数相关的知识,希望能为你提供帮助。
我必须上传一个文件,还有三个参数,这是string。文件可以是图像或zip.How是否可以使用volley上传file并在点击按钮时提交string参数?
我也试过这个链接-https://www.simplifiedcoding.net/upload-pdf-file-server-android/请帮帮我。谢谢!!我的代码是:

public class Tab1Fragment extends Fragment implements AdapterView.OnItemSelectedListener {EditText subj,desx; private ImageView mAvatarImage; Button choosefile,select,submt; String uid, type; String MY_PREFS_NAME = "value"; private int PICK_PDF_REQUEST = 1; TextView filetext; //storage permission code private static final int STORAGE_PERMISSION_CODE = 123; String uploadId; //Uri to store the image uri private Uri filePath; Spinner spinner,spinner2; public Tab1Fragment() { // Required empty public constructor } public static Tab1Fragment newInstance() { Tab1Fragment fragment = new Tab1Fragment(); return fragment; }@Override public void onActivityCreated(Bundle savedInstanceState) {super.onActivityCreated(savedInstanceState); }@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View rootview= inflater.inflate(R.layout.fragment_tab1, container, false); subj=(EditText)rootview.findViewById(R.id.subj); choosefile=(Button)rootview.findViewById(R.id.choosefile); select=(Button)rootview.findViewById(R.id.select); submt=(Button)rootview.findViewById(R.id.submt); filetext=(TextView)rootview.findViewById(R.id.filetext); mAvatarImage=(ImageView)rootview.findViewById(R.id.image); desx=(EditText)rootview.findViewById(R.id.desx); submt.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { saveProfileAccount(); } }); select.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { showFileChooser(); } }); choosefile.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { uploadMultipart(); } }); requestStoragePermission(); SharedPreferences prefs = this.getActivity().getSharedPreferences(MY_PREFS_NAME, Context.MODE_PRIVATE); uid = prefs.getString("uid", null); spinner = (Spinner)rootview.findViewById(R.id.spinner); spinner2 = (Spinner)rootview.findViewById(R.id.spinner2); // Spinner click listener spinner.setOnItemSelectedListener(this); spinner2.setOnItemSelectedListener(this); // Spinner Drop down elements List< String> deparment= new ArrayList< String> (); deparment.add("Support"); deparment.add("Project"); deparment.add("Payment"); deparment.add("Service"); ArrayAdapter< String> dataAdapter = new ArrayAdapter< String> (this.getActivity(),android.R.layout.simple_spinner_item, deparment); // Drop down layout style - list view with radio button dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // attaching data adapter to spinner spinner.setAdapter(dataAdapter); List< String> priority= new ArrayList< String> (); priority.add("low"); priority.add("Medium"); priority.add("High"); ArrayAdapter< String> dataAdapter2 = new ArrayAdapter< String> (this.getActivity(),android.R.layout.simple_spinner_item, priority); // Drop down layout style - list view with radio button dataAdapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // attaching data adapter to spinner spinner2.setAdapter(dataAdapter2); return rootview; }private void saveProfileAccount() {VolleyMultipartRequest multipartRequest = new VolleyMultipartRequest(Request.Method.POST, Constants.UPLOAD_SUPPORT, new Response.Listener< NetworkResponse> () { @Override public void onResponse(NetworkResponse response) { String resultResponse = new String(response.data); try { JSONObject b = new JSONObject(resultResponse); int status = b.getInt("status"); String data = https://www.songbingjia.com/android/b.getString("message"); Log.d("Response", data); if (status ==100) { /*Intent intent = new Intent(getActivity(),Skills.class); startActivity(intent); */Toast.makeText(getActivity(), data, Toast.LENGTH_SHORT).show(); }} catch (JSONException e) { e.printStackTrace(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { NetworkResponse networkResponse = error.networkResponse; String errorMessage = "Unknown error"; if (networkResponse == null) { if (error.getClass().equals(TimeoutError.class)) { errorMessage = "Request timeout"; } else if (error.getClass().equals(NoConnectionError.class)) { errorMessage = "Failed to connect server"; } } else { String result = new String(networkResponse.data); try { JSONObject response = new JSONObject(result); String status = response.getString("status"); String message = response.getString("message"); Log.e("Error Status", status); Log.e("Error Message", message); if (networkResponse.statusCode == 404) { errorMessage = "Resource not found"; } else if (networkResponse.statusCode == 401) { errorMessage = message+" Please login again"; } else if (networkResponse.statusCode == 400) { errorMessage = message+ " Check your inputs"; } else if (networkResponse.statusCode == 500) { errorMessage = message+" Something is getting wrong"; } } catch (JSONException e) { e.printStackTrace(); } } Log.i("Error", errorMessage); error.printStackTrace(); } }) { @Override protected Map< String, String> getParams() { Map< String, String> params = new HashMap< > (); params.put("userid", uid); params.put("department", spinner.getSelectedItem().toString()); params.put("priority", spinner2.getSelectedItem().toString().trim()); params.put("subject", subj.getText().toString().trim()); params.put("description",desx.getText().toString().trim()); return params; }@Override protected Map< String, DataPart> getByteData() { Map< String, DataPart> params = new HashMap< > (); // file name could found file base or direct access from real path // for now just get bitmap data from ImageView params.put("avatar", new DataPart("file_avatar.jpg", AppHelper.getFileDataFromDrawable(getContext(), mAvatarImage.getDrawable()), "*/*")); return params; } }; VolleySingleton.getInstance(getContext()).addToRequestQueue(multipartRequest); }

答案试试这个
public void fileUploadFunction() {// Getting file path using Filepath class. Pdfuri = FilePath.getPath(this, uri); Log.d("Pdfuri", Pdfuri); // If file path object is null then showing toast message to move file into internal storage. if (Pdfuri == null) {Toast.makeText(this, "Please move your PDF file to internal storage & try again.", Toast.LENGTH_LONG).show(); } // If file path is not null then PDF uploading file process will starts. else {try {PdfID = UUID.randomUUID().toString(); new MultipartUploadRequest(this, PdfID, AppConstants.URL) .addFileToUpload(Pdfuri, "pdf") .addParameter("course", course.trim()) .addParameter("course_id", c_id.trim()) .addParameter("stream", stream.trim()) .setNotificationConfig(new UploadNotificationConfig()) .setMaxRetries(5) .startUpload(); Toast.makeText(MainActivity.this,"Successfully Uploaded",Toast.LENGTH_SHORT).show(); } catch (Exception exception) {Toast.makeText(this, exception.getMessage(),Toast.LENGTH_SHORT).show(); } } }

另一答案
VolleyMultipartRequest multipartRequest = new VolleyMultipartRequest(Request.Method.POST, url, new Response.Listener< NetworkResponse> () { @Override public void onResponse(NetworkResponse response) { //Read response here } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { error.printStackTrace(); } }) { @Override protected Map< String, String> getParams() { Map< String, String> params = new HashMap< > (); //Add post values here return params; }@Override protected Map< String, DataPart> getByteData() { Map< String, DataPart> params = new HashMap< > (); // Add you file here return params; } }; VolleySingleton.getInstance(getBaseContext()).addToRequestQueue(multipartRequest);

【在android中上传文件和其他字符串参数】你可以使用multipart。这是一个示例代码

    推荐阅读