android上傳圖片並附帶上傳資料,檔案流

來源:互聯網
上載者:User

標籤:圖片上傳 檔案流   android   

關於android的圖片上傳有兩種方式,一種是以檔案流的方式上傳,圖片轉換成二進位上穿。另一種是把圖片轉成base64方式上傳,這篇部落格我只介紹檔案流,關於base64方式會在下一篇部落格中介紹!

      首先是安卓端;圖片上傳我們需要一個圖片的路徑,同過調用本地相簿或者拍照可以返回圖片路徑,這個在這裡就不說了;假設我們獲得圖片路徑為PicPath;

下面是安卓代碼:

首先我們要封裝要發送的資料 資料封裝好了以後用String path=URLEncodedUtils.format(Parameters,"UTF-8");來編碼; 然後是開線程發送資料

activity:

封裝資料

@SuppressLint("SimpleDateFormat")
public String  getrubbishIfo() throws IOException {
final List<NameValuePair> Parameters = new ArrayList<NameValuePair>();
Parameters.add(new BasicNameValuePair("runame", thingname.getText()
.toString().trim()));
Parameters.add(new BasicNameValuePair("ruleibie", fenlei
.getSelectedItem().toString()));
Parameters.add(new BasicNameValuePair("rubeizhu", beizhu.getText()
.toString().trim()));
Parameters.add(new BasicNameValuePair("rufreetime", freetime
.getSelectedItem().toString()));
Parameters.add(new BasicNameValuePair("userphone", userphone));
Parameters.add(new BasicNameValuePair("address", address.getText()
.toString().trim()));
Parameters.add(new BasicNameValuePair("username", username));
Parameters.add(new BasicNameValuePair("rudate", ""));


System.out.println("Parameters:" + Parameters);
String path=URLEncodedUtils.format(Parameters,"UTF-8");
System.out.println(path+"0000000000000000000");
return path;

}

Handler myhandler = new Handler() {
public void handleMessage(Message msg) {
String text = (String) msg.obj;
if (text.equals("yes")) {
Log.d("click", "不為空白了");
Toast.makeText(getApplicationContext(), "發布成功!!!", Toast.LENGTH_SHORT)
.show();
} else {
Toast.makeText(getApplicationContext(), "發布失敗!!!",
Toast.LENGTH_LONG).show();
}
};
};

//提交資料

class tijiaoListener implements OnClickListener {


@Override
public void onClick(View v) {
// TODO Auto-generated method stub


new Thread(new Runnable() {


@Override
public void run() {
// TODO Auto-generated method stub

UploadFile_image up=new UploadFile_image();

try {
String path = getrubbishIfo();
String restr=up.uploadFile(HttpPath.FABU_PATH+"?"+path, picpath);//HttpPath.FABU_PATH為路徑,將封裝好的資料path綁到路徑後傳遞給伺服器,picpath為圖片路徑
Message message = myhandler.obtainMessage();
message.obj = restr;
myhandler.sendMessage(message);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}
}).start();

下邊是工具類UploadFile_image up也就是圖片格式准換的方式;

package com.back.util;


import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class UploadFile_image {
private String newName ="image.jpg";
 /* 上傳檔案至Server的方法 */
    public  String uploadFile(String actionUrl,String picPath)
    {
      String end ="\r\n";
      String twoHyphens ="--";
      String boundary ="*****";//邊界標識
      try
      {
        URL url =new URL(actionUrl);
        HttpURLConnection con=(HttpURLConnection)url.openConnection();
        /* 允許Input、Output,不使用Cache */
        con.setDoInput(true);//允許輸入資料流
        con.setDoOutput(true);//允許輸出資料流
        con.setUseCaches(false);//不允許使用緩衝
        /* 設定傳送的method=POST */
        con.setRequestMethod("POST");
        /* setRequestProperty   設定編碼  */
        con.setRequestProperty("Connection", "Keep-Alive");
        con.setRequestProperty("Charset", "UTF-8");
        con.setRequestProperty("Content-Type",// "multipart/form-data"這個參數來說明我們這傳的是檔案不是字串了
                           "multipart/form-data;boundary="+boundary); 
        /* 設定DataOutputStream */
        DataOutputStream ds =
          new DataOutputStream(con.getOutputStream());
        ds.writeBytes(twoHyphens + boundary + end);
        ds.writeBytes("Content-Disposition: form-data; "+
                      "name=\"file1\";filename=\""+
                      newName +"\""+ end);  
        ds.writeBytes(end); 


        /* 取得檔案的FileInputStream */
        FileInputStream fStream =new FileInputStream(picPath);
        /* 設定每次寫入1024bytes */
        int bufferSize =1024;
        byte[] buffer =new byte[bufferSize];
        int length =-1;
        /* 從檔案讀取資料至緩衝區 */
        while((length = fStream.read(buffer)) !=-1)
        {
          /* 將資料寫入DataOutputStream中 */
          ds.write(buffer, 0, length);
        }
        ds.writeBytes(end);
        ds.writeBytes(twoHyphens + boundary + twoHyphens + end);
        /* close streams */
        fStream.close();
        ds.flush();
        /* 取得Response內容 */
        InputStream is = con.getInputStream();
        int ch;
        StringBuffer b =new StringBuffer();
        while( ( ch = is.read() ) !=-1 )
        {
          b.append( (char)ch );
        }
        /* 將Response顯示於Dialog */
       
      //  showDialog("上傳成功"+b.toString().trim());
        /* 關閉DataOutputStream */
        ds.close();
        //返回用戶端返回的資訊
        return b.toString().trim();
      }
      catch(Exception e)
      {
        //showDialog("上傳失敗"+e);
     return null;
      }
    }
}

安卓端結束;

下邊是伺服器端代碼

package cn.back.servlet.app;


import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.URLDecoder;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.DiskFileUpload;
import org.apache.commons.fileupload.FileItem;
import cn.back.domin.Things;
import cn.back.service.backservice;
import cn.back.service.backserviceImp;


public class UploadImageapp extends HttpServlet {
private String name;
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}


public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException { 
//接受圖片
String temp = request.getSession().getServletContext().getRealPath("/")
+ "temp"; // 臨時目錄
System.out.println("temp=" + temp);
String loadpath = request.getSession().getServletContext()
.getRealPath("/")
+ "imagething"; // 上傳檔案存放目錄


System.out.println("loadpath=" + loadpath);
DiskFileUpload fu = new DiskFileUpload();
fu.setSizeMax(1 * 1024 * 1024); // 設定允許使用者上傳檔案大小,單位:位元組
fu.setSizeThreshold(4096); // 設定最多隻允許在記憶體中儲存的資料,單位:位元組
fu.setRepositoryPath(temp); // 設定一旦檔案大小超過getSizeThreshold()的值時資料存放在硬碟的目錄


// 開始讀取上傳資訊
int index = 0;
List fileItems = null;


try {
fileItems = fu.parseRequest(request);
System.out.println("fileItems=" + fileItems);
} catch (Exception e) {
e.printStackTrace();
}


Iterator iter = fileItems.iterator(); // 依次處理每個上傳的檔案
while (iter.hasNext()) {
FileItem item = (FileItem) iter.next();// 忽略其他不是檔案域的所有表單資訊
if (!item.isFormField()) {
name = item.getName();// 擷取上傳檔案名稱,包括路徑
name = name.substring(name.lastIndexOf("\\") + 1);// 從全路徑中提取檔案名稱
long size = item.getSize();
if ((name == null || name.equals("")) && size == 0)
continue;
int point = name.indexOf(".");
// name=(new
// Date()).getTime()+name.substring(point,name.length())+index;
name = (new Date()).getTime()
+ name.substring(point, name.length());
index++;
File fNew = new File(loadpath,name);
try {
item.write(fNew);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}


} else// 取出不是檔案域的所有表單資訊
{
String fieldvalue = item.getString();
// 如果包含中文應寫為:(轉為UTF-8編碼)
// String fieldvalue = new String(item.getString().getBytes(),"UTF-8");
}
}
//圖片接受完畢

//接收資料並儲存
String path="/back/imagething/"+name;
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
Date now = new Date();
DateFormat dataFormat = new SimpleDateFormat("yyyy/MM/dd hh:mm:ss");// 2014/08/31// 04:08:26擷取時間
String fabutime = dataFormat.format(now);
backservice bs = new backserviceImp();
Things t = new Things();
t.setThingname(new String(request.getParameter("runame").getBytes("ISO_8859-1"),"UTF-8"));

          //由於是用URLEncodedUtils編碼所以解碼比較麻煩,關於解碼我有一篇單獨的部落格寫編碼
System.out.println(name+"11111111111111111111111");
t.setThingleibie(new String(request.getParameter("ruleibie").getBytes("ISO_8859-1"),"UTF-8"));
t.setThingbeizhu(new String(request.getParameter("rubeizhu").getBytes("ISO_8859-1"),"UTF-8"));
t.setThingfreetime(new String(request.getParameter("rufreetime").getBytes("ISO_8859-1"),"UTF-8"));
t.setThingimg(path);
t.setThingfabutime(fabutime);
t.setUsername(new String(request.getParameter("username").getBytes("ISO_8859-1"),"UTF-8"));
t.setUserphone(new String(request.getParameter("userphone").getBytes("ISO_8859-1"),"UTF-8"));
t.setAddress(new String(request.getParameter("address").getBytes("ISO_8859-1"),"UTF-8"));
int flag = bs.addBack(t);
if (flag != 0) {
System.out.println("app註冊成功");
}else
{
System.out.println("0000000000000");
}
//發送資料

response.setContentType("text/plain");
response.setCharacterEncoding("UTF-8");
PrintWriter out = response.getWriter();//發送資料
out.write("yes");
out.flush();
out.close();
}
}

伺服器端結束;大功告成,關於base64上傳,會在下一篇部落格中寫。如有疑問聯絡[email protected]




android上傳圖片並附帶上傳資料,檔案流

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.