android 上传文件
来源:互联网 发布:算法里的mod是切莫意思 编辑:程序博客网 时间:2024/06/03 02:26
android端: HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(_URL + "uploadFile"); String uploadMsg = "上传 照片失败!"; try { List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); // Your DATA nameValuePairs.add(new BasicNameValuePair("filename", ("IMAGE.jpg")) ); File aFile = new File(photoPath); Log.i("System.out", "info -- photoPath: " + photoPath); FileEntity fileEty = new FileEntity(aFile, "binary/octet-stream"); httppost.setEntity(fileEty); httppost.addHeader("filename", aFile.getName()); HttpResponse response; response = httpclient.execute(httppost); //Log.i("info -- response: ", response.getStatusLine().getReasonPhrase()); Header[] headers = response.getAllHeaders(); headers = response.getHeaders("resultcode"); if (headers[0].getValue().equals("0")) { uploadMsg = "上传照片成功!"; } } catch (UnsupportedEncodingException e) { //e.printStackTrace(); uploadMsg += e.toString(); Log.e("System.out", e.toString()); } catch (ClientProtocolException e) { //e.printStackTrace(); uploadMsg += e.toString(); Log.e("System.out", e.toString()); } catch (IOException e) { //e.printStackTrace(); uploadMsg += e.toString(); Log.e("System.out", e.toString()); } finally { Log.i("System.out", "uploadMsg = " + uploadMsg); httpclient.getConnectionManager().shutdown(); Log.e("System.out", "time = " + (System.currentTimeMillis() - l)); } } private void uploadFile2Svr2() { BufferedReader in = null; HttpClient httpclient = new DefaultHttpClient(); URL url = null; try { url = new URL(_URL + "uploadFile"); } catch (MalformedURLException e1) { e1.printStackTrace(); } HttpURLConnection conn = null; DataOutputStream dos = null; String lineEnd = "/r/n"; String twoHyphens = "--"; String boundary = "*****"; int maxBufferSize = 16 * 1024; try { //httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); // Open a HTTP connection to the URL conn = (HttpURLConnection) url.openConnection(); conn.setConnectTimeout(120000); // Allow Inputs conn.setDoInput(true); // Allow Outputs conn.setDoOutput(true); // Don't use a cached copy. conn.setUseCaches(false); // Use a post method. conn.setRequestMethod("POST"); conn.setRequestProperty("Connection", "Keep-Alive"); conn.setRequestProperty("Content-Type", //"multipart/form-data;boundary=" + boundary); "application/x-www-form-urlencoded"); conn.setRequestProperty("user-agent", "Mozilla/5.0 (Windows; U; Windows NT 5.2; zh-CN; rv:1.9.1.6) Gecko/20091201 Firefox/3.5.6 GTB6"); //conn.setRequestProperty("accept-language", "zh-cn,zh;q=0.5"); //conn.setRequestProperty("Content-Type", "multipart/form-data;boundary="+ boundary); conn.connect(); //OutputStream connOs = conn.getOutputStream(); dos = new DataOutputStream(conn.getOutputStream()); dos.writeBytes(twoHyphens + boundary + lineEnd); dos.writeBytes("Content-Disposition: form-data; name="uploadedfile";filename="" + "exsistingFileName" + """ + lineEnd); //dos.writeBytes(lineEnd); Log.i("System.out", "Headers are written"); // upload file to webserver via http FileInputStream fileInputStream = new FileInputStream(photoPath); // create a buffer of maximum size int bytesAvailable = fileInputStream.available(); int bufferSize = Math.min(bytesAvailable, maxBufferSize); byte[] buffer = new byte[bufferSize]; // read file and write it into form... int bytesRead = fileInputStream.read(buffer, 0, bufferSize); while (bytesRead > 0) { dos.write(buffer, 0, bufferSize); bytesAvailable = fileInputStream.available(); bufferSize = Math.min(bytesAvailable, maxBufferSize); bytesRead = fileInputStream.read(buffer, 0, bufferSize); } // send multipart form data necesssary after file data... dos.writeBytes(lineEnd); dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd); // close streams Log.e("System.out", "File is written"); fileInputStream.close(); dos.flush(); dos.close(); dos = null; // response // HttpResponse response; // response = httpclient.execute(httppost); // response = httpclient.execute(conn.get); in = new BufferedReader( new InputStreamReader(conn.getInputStream())); StringBuffer sb = new StringBuffer(""); String line = ""; String NL = System.getProperty("line.separator"); while ((line = in.readLine()) != null) { sb.append(line + NL); } in.close(); String result = sb.toString(); Log.i("System.out", result); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally{ if(in != null){ try{ in.close(); }catch(IOException ioe){ Log.e("System.out", ioe.toString()); } } } }
private static final String OPPOSITE_OBLIQUE_LINE = "////"; private static final String WEBPOSITION = "webapps"; private static final String SBPATH = "UploadedFiles/"; File outdir = null; File outfile = null; FileOutputStream fos = null; BufferedInputStream bis = null; byte[] bs = new byte[1024]; String uploadFName = null; try { StringBuffer destFName = new StringBuffer(); destFName.append("/mnt/sdcard/").append(SBPATH); outdir = new File(destFName.toString()); request.setCharacterEncoding("UTF-8"); uploadFName = request.getParameter("filename"); //name of uploaded file uploadFName = request.getHeader("filename"); if (isEmpty(uploadFName)) uploadFName = "filename.jpg"; //orderNo = request.getParameter("orderno"); //id of the order or work sheet //userId = request.getParameter("userid"); //id of the user who upload the file //attachType = request.getParameter("attach_type"); //type of attachment, refer to file.FileBean's definition String desc = request.getParameter("desc"); //description of uploaded file if (desc==null) desc = ""; if (true) { destFName.append(getDatedFName(uploadFName)); outfile = new File(destFName.toString()); bis = new BufferedInputStream(request.getInputStream()); uploadFile(); //response.getWriter().write("0"); //success response.setHeader("resultcode", "0"); } else if (desc.length() > 400/2) { //response.getWriter().write("3"); //illegal description response.setHeader("resultcode", "3"); } else { System.out.println("调用格式错误!"); response.sendError(100, "参数错误!"); //response.getWriter().write("1"); response.setHeader("resultcode", "1"); //parameter error //return; } } catch (Exception e) { //response.getWriter().write("7"); //failure response.setHeader("resultcode", "7"); e.printStackTrace(); } finally { if (null != bis) bis.close(); if (null != fos) fos.close(); }
{ if (!outdir.exists()) outdir.mkdir(); if (!outfile.exists()) outfile.createNewFile(); fos = new FileOutputStream(outfile); int i; while ((i = bis.read(bs)) != -1) { fos.write(bs, 0, i); } } public static String getDatedFName(String fname) { StringBuffer result = new StringBuffer(); SimpleDateFormat df = new SimpleDateFormat("yyMMddHHmmss"); String dateSfx = "_" + df.format(new Date()); int idx = fname.lastIndexOf('.'); if (idx != -1) { result.append(fname.substring(0, idx)); result.append(dateSfx); result.append(fname.substring(idx)); } else { result.append(fname); result.append(dateSfx); } return result.toString(); } public static String getUrlFName(String fname, HttpServletRequest request) { String result = ""; if (isEmpty(fname)) return result; try { if (fname.startsWith("http://")) { result = fname; } else { //HttpServletRequest request = ServletActionContext.getServletContext().getRgetRequest(); //UserAndOrganAndRole user = (UserAndOrganAndRole)request.getSession().getAttribute("user"); String ip = request.getServerName(); int port = request.getServerPort(); result = fname.substring(fname.indexOf(SBPATH)); StringBuffer tmpBuff = new StringBuffer(); tmpBuff.append("http://").append(ip).append(":").append(port).append(OBLIQUE_LINE).append(result); //Sample: http://localhost:8083/UploadedFiles/IMAGE_067_100222102521.jpg result = tmpBuff.toString(); } } catch (Exception ex) { ex.printStackTrace(); } System.out.println("result is: "+result); return result; } public static boolean isEmpty(String str) { return ((str == null) || (str.length() == 0)); } private String getRealDir(String newFileNameRoot) throws Exception { if (newFileNameRoot == null) throw new Exception("get real dir failed !"); int dp = newFileNameRoot .lastIndexOf(OBLIQUE_LINE); if (dp == -1) throw new Exception("invalid path !"); int dpbefore = newFileNameRoot.lastIndexOf( OBLIQUE_LINE, dp - 1); if (dpbefore == -1) throw new Exception("invalid path !"); String needSubStr = newFileNameRoot.substring(dpbefore + 1, dp); String nextStr = newFileNameRoot.substring(0, dpbefore + 1); if (!needSubStr.trim().equals(WEBPOSITION)) { return getRealDir(nextStr); } else return newFileNameRoot; }
private String photoPath = Configuration.SD_CARD_PATH + "/123.jpg";
public void uploadFile2Svr() {
long l = System.currentTimeMillis();
// nameValuePairs.add(new BasicNameValuePair("orderno", "1"));
// nameValuePairs.add(new BasicNameValuePair("userid", "123"));
// nameValuePairs.add(new BasicNameValuePair("attach_type", "1"));
// httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
// // Your DATA
// nameValuePairs.add(new BasicNameValuePair("filename", getDatedFName("IMAGE.jpg")) );
// nameValuePairs.add(new BasicNameValuePair("orderno", "1"));
// nameValuePairs.add(new BasicNameValuePair("userid", "123"));
// nameValuePairs.add(new BasicNameValuePair("attach_type", "1"));
servlet:
private static final String OBLIQUE_LINE = "/";
private void doUplaodFile(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String root = this.getServletContext().getRealPath("/");
root = root.replaceAll("////", "/");
// destFName.append(getRealDir(root)).append(SBPATH);
}
private void uploadFile() throws IOException
System.out.println("outdir:" + outdir.getPath());
System.out.println("outfile:" + outfile.getPath());
- android http上传文件
- Android 上传大文件
- Android 上传大文件
- android 文件上传
- android 上传文件类
- android上传文件
- Android 文件上传参考
- Android 文件的上传
- Android入门:文件上传
- android之文件上传
- Android 上传文件
- Android上传文件,续
- android httpclient 上传文件
- android 文件上传
- Android中的文件上传
- android 文件上传
- Android文件上传
- Android文件上传
- iOS开发之keychain的使用
- Oracle小结--2
- Extjs4中的Form之下拉列表combobox的使用
- shell常用配置文件
- ORA-02291: 违反完整约束条件 解决方法
- android 上传文件
- C语言电子书
- lwIP配置文件opt.h和lwipopts.h初步分析
- ubuntu12.04 安装软件过程中无法选中确定问题
- Android如何防止apk程序被反编译
- 大众点评api接口 asp.net实例
- xml解析(GBK)
- android 当前日期的前后n天的用法
- 火狐和谷歌浏览器屏蔽键盘按键Backspace回退网页