安卓之上传文件,即HTTP提交表单
獲取文件:
??? public void Init()
??? {
??????? noScrollgridview = (GridView) findViewById(R.id.noScrollgridview);
??????? noScrollgridview.setSelector(new ColorDrawable(Color.TRANSPARENT));
??????? adapter = new GridAdapter(this);
??????? adapter.update1();
??????? noScrollgridview.setAdapter(adapter);
??????? noScrollgridview.setOnItemClickListener(new OnItemClickListener()
??????? {
??????????? public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
??????????????????? long arg3)
??????????? {
??????????????? InputMethodManager imm = ( InputMethodManager ) arg1.getContext( ).getSystemService( Context.INPUT_METHOD_SERVICE );??
???????????????? imm.hideSoftInputFromWindow( arg1.getApplicationWindowToken( ) , 0 );??
??????????????? if (arg2 == Bimp.bmp.size())
??????????????? {
??????????????????? new PopupWindows(PublishedActivity.this, noScrollgridview);
??????????????? }
??????????????? else
??????????????? {
??????????????????? Intent intent = new Intent(PublishedActivity.this,
??????????????????????????? PhotoActivity.class);
??????????????????? intent.putExtra("ID", arg2);
??????????????????? startActivity(intent);
??????????????? }
??????????? }
??????? });
??????? activity_selectimg_send = (Button) findViewById(R.id.activity_selectimg_send);
??????? activity_selectimg_send.setOnClickListener(new OnClickListener() {
??????????? public void onClick(View v) {
??????? //showDialog("ddd");
??????? StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
??????? .permitNetwork().build());
??????? List<String> list = new ArrayList<String>();
??????? for (int i = 0; i < Bimp.drr.size(); i++)
??????? {
??????????? String Str = Bimp.drr.get(i).substring(
??????????????????? Bimp.drr.get(i).lastIndexOf("/") + 1,
??????????????????? Bimp.drr.get(i).lastIndexOf("."));
??????????? list.add(FileUtils.SDPATH + Str + ".JPEG");
??????????? String path = Bimp.drr.get(i);
//??????????? showDialog(path);
//??????????? showDialog(getDataValue("_member_id"));
//??????????? showDialog(((TextView) findViewById(R.id.activity_selectxxx_send)).getText().toString());
??????????? String fileKey = "imgFile";?
?????????????????? UploadUtil uploadUtil = UploadUtil.getInstance();;?
????????????????? uploadUtil.setOnUploadProcessListener(PublishedActivity.this);? //設(shè)置監(jiān)聽器監(jiān)聽上傳狀態(tài)?
?????????????????? Map<String, String> params = new HashMap<String, String>();?
?????????????????? params.put("userid", getDataValue("_member_id"));?
?????????????????? params.put("content", ((TextView) findViewById(R.id.activity_selectxxx_send)).getText().toString());?
?????????????????? uploadUtil.uploadFile( path,fileKey, "http://shop.tminji.com/sns/SendAMessage",params);
??????????? //String x = ((TextView)v.findViewById(R.id.activity_selectxxx_send)).getText().toString();
??????????? //uploadFile(path);
??????? }
??????? // 高清的壓縮圖片全部就在 list 路徑里面了
??????? // 高清的壓縮過的 bmp 對象 都在 Bimp.bmp里面
??????? // 完成上傳服務(wù)器后 .........
??????? showDialog("發(fā)布成功^_^");
??????? FileUtils.deleteDir();
//??????? Intent intent = new Intent(PublishedActivity.this, MainActivity.class);
//??????? Bundle bundle = new Bundle();?
//??????? /*字符、字符串、布爾、字節(jié)數(shù)組、浮點(diǎn)數(shù)等等,都可以傳*/?
//??????? bundle.putString("Name", "feng88724");?
//??????? /*把bundle對象assign給Intent*/?
//???????
//??????? intent.setClass(PublishedActivity.this, MainActivity.class);
//??????? intent.putExtras(bundle);?
//??????? startActivity(intent);
??????? Intent intentx = new Intent(PublishedActivity.this, MainActivity.class);?
??????? /* 通過Bundle對象存儲需要傳遞的數(shù)據(jù) */?
??????? Bundle bundle = new Bundle();?
??????? /*字符、字符串、布爾、字節(jié)數(shù)組、浮點(diǎn)數(shù)等等,都可以傳*/?
??????? bundle.putString("Name", "feng88724");?
??????? /*把bundle對象assign給Intent*/?
??????? intentx.putExtras(bundle);?
??????? startActivity(intentx);?
??????? }});
??? }
?
上傳文件
private void toUploadFile(File file, String fileKey, String RequestURL,
??????? Map<String, String> param) {
??? String result = null;
??? requestTime= 0;
??? long requestTime = System.currentTimeMillis();
??? long responseTime = 0;
??? try {
??????? URL url = new URL(RequestURL);
??????? HttpURLConnection conn = (HttpURLConnection) url.openConnection();
??????? conn.setReadTimeout(readTimeOut);
??????? conn.setConnectTimeout(connectTimeout);
??????? conn.setDoInput(true); // 允許輸入流
??????? conn.setDoOutput(true); // 允許輸出流
??????? conn.setUseCaches(false); // 不允許使用緩存
??????? conn.setRequestMethod("POST"); // 請求方式
??????? conn.setRequestProperty("Charset", CHARSET); // 設(shè)置編碼
??????? conn.setRequestProperty("connection", "keep-alive");
??????? conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
??????? conn.setRequestProperty("Content-Type", CONTENT_TYPE + ";boundary=" + BOUNDARY);
??????? //conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
??????? /**
???????? * 當(dāng)文件不為空,把文件包裝并且上傳
???????? */
??????? DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
??????? StringBuffer sb = null;
??????? String params = "";
??????? /***
???????? * 以下是用于上傳參數(shù)
???????? */
??????? if (param != null && param.size() > 0) {
??????????? Iterator<String> it = param.keySet().iterator();
??????????? while (it.hasNext()) {
??????????????? sb = null;
??????????????? sb = new StringBuffer();
??????????????? String key = it.next();
??????????????? String value = param.get(key);
??????????????? sb.append(PREFIX).append(BOUNDARY).append(LINE_END);
??????????????? sb.append("Content-Disposition: form-data; name=\"").append(key).append("\"").append(LINE_END).append(LINE_END);
??????????????? sb.append(value).append(LINE_END);
??????????????? params = sb.toString();
??????????????? Log.i(TAG, key+"="+params+"##");
??????????????? dos.write(params.getBytes());
??????????????? //dos.flush();
??????????? }
??????? }
??????? sb = null;
??????? params = null;
??????? sb = new StringBuffer();
??????? /**
???????? * 這里重點(diǎn)注意: name里面的值為服務(wù)器端需要key 只有這個key 才可以得到對應(yīng)的文件
???????? * filename是文件的名字,包含后綴名的 比如:abc.png
???????? */
??????? sb.append(PREFIX).append(BOUNDARY).append(LINE_END);
??????? sb.append("Content-Disposition:form-data; name=\"" + fileKey
??????????????? + "\"; filename=\"" + file.getName() + "\"" + LINE_END);
??????? sb.append("Content-Type:image/pjpeg" + LINE_END); // 這里配置的Content-type很重要的 ,用于服務(wù)器端辨別文件的類型的
??????? sb.append(LINE_END);
??????? params = sb.toString();
??????? sb = null;
??????? Log.i(TAG, file.getName()+"=" + params+"##");
??????? dos.write(params.getBytes());
??????? /**上傳文件*/
??????? InputStream is = new FileInputStream(file);
??????? onUploadProcessListener.initUpload((int)file.length());
??????? byte[] bytes = new byte[1024];
??????? int len = 0;
??????? int curLen = 0;
??????? while ((len = is.read(bytes)) != -1) {
??????????? curLen += len;
??????????? dos.write(bytes, 0, len);
??????????? onUploadProcessListener.onUploadProcess(curLen);
??????? }
??????? is.close();
??????? dos.write(LINE_END.getBytes());
??????? byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINE_END).getBytes();
??????? dos.write(end_data);
??????? dos.flush();
??????? //dos.write(tempOutputStream.toByteArray());
??????? /**
???????? * 獲取響應(yīng)碼 200=成功 當(dāng)響應(yīng)成功,獲取響應(yīng)的流
???????? */
??????? int res = conn.getResponseCode();
??????? responseTime = System.currentTimeMillis();
??????? this.requestTime = (int) ((responseTime-requestTime)/1000);
??????? Log.e(TAG, "response code:" + res);
??????? if (res == 200) {
??????????? Log.e(TAG, "request success");
??????????? InputStream input = conn.getInputStream();
??????????? StringBuffer sb1 = new StringBuffer();
??????????? int ss;
??????????? while ((ss = input.read()) != -1) {
??????????????? sb1.append((char) ss);
??????????? }
??????????? result = sb1.toString();
??????????? Log.e(TAG, "result : " + result);
??????????? sendMessage(UPLOAD_SUCCESS_CODE, "上傳結(jié)果:"
??????????????????? + result);
??????????? return;
??????? } else {
??????????? Log.e(TAG, "request error");
??????????? sendMessage(UPLOAD_SERVER_ERROR_CODE,"上傳失敗:code=" + res);
??????????? return;
??????? }
??? } catch (MalformedURLException e) {
??????? sendMessage(UPLOAD_SERVER_ERROR_CODE,"上傳失敗:error=" + e.getMessage());
??????? e.printStackTrace();
??????? return;
??? } catch (IOException e) {
??????? sendMessage(UPLOAD_SERVER_ERROR_CODE,"上傳失敗:error=" + e.getMessage());
??????? e.printStackTrace();
??????? return;
??? }
}
轉(zhuǎn)載于:https://www.cnblogs.com/luminji/p/4603630.html
總結(jié)
以上是生活随笔為你收集整理的安卓之上传文件,即HTTP提交表单的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 什么是OpenCL?面向FPGA的Ope
- 下一篇: vim配置文件~/.vimrc