上传图片到服务器首先要在SD卡上生成一个图片。
- Java 代码复制内容到剪贴板
- String path = Environment.getDataDirectory().getPath() + "/data/" +
- getPackageName() + "/" + "upload.jpg";
- File file = new File(path);
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- bitMap.compress(Bitmap.CompressFormat.PNG, 85, baos); //bitMap是要上传的图片Bitmap
- byte[] photoBytes = baos.toByteArray();
- if (!file.exists())
- file.createNewFile();
- FileOutputStream fos = new FileOutputStream(file);
- fos.write(photoBytes);
- fos.flush();
- fos.close();
然后再调用下面的方法:
- Java 代码复制内容到剪贴板
- /**
- * 上传文件和文字
- * @param aFile
- * @param status
- * @param urlPath
- * @return
- */
- public boolean uploadStatus(File aFile, String status, String urlPath) {
- boolean result = false;
- try {
- URL url = new URL(urlPath);
- HttpURLConnection request = (HttpURLConnection) url
- .openConnection();
- request.setDoOutput(true);
- request.setRequestMethod("POST");
- String boundary = "---------------------------37531613912423";
- String content = "--"
- + boundary
- + "\r\nContent-Disposition: form-data; name=\"status\"\r\n\r\n";
- String pic = "\r\n--"
- + boundary
- + "\r\nContent-Disposition: form-data; name=\"pic\"; " +
- "filename=\"image.jpg\"\r\nContent-Type: image/jpeg\r\n\r\n";
- byte[] end_data = ("\r\n--" + boundary + "--\r\n").getBytes();
- FileInputStream stream = new FileInputStream(aFile);
- byte[] file = new byte[(int) aFile.length()];
- stream.read(file);
- request.setRequestProperty("Content-Type",
- "multipart/form-data; boundary=" + boundary); // 设置表单类型和分隔符
- request.setRequestProperty(
- "Content-Length",
- String.valueOf(content.getBytes().length
- + status.getBytes().length + pic.getBytes().length
- + aFile.length() + end_data.length)); // 设置内容长度
- OutputStream ot = request.getOutputStream();
- ot.write(content.getBytes());
- ot.write(status.getBytes());
- ot.write(pic.getBytes());
- ot.write(file);
- ot.write(end_data);
- ot.flush();
- ot.close();
- request.connect();
- if (200 == request.getResponseCode()) {
- result = true;
- } else {
- result = false;
- }
- } catch (FileNotFoundException e1) {
- e1.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- }
- return result;
- }
本文转自06peng 51CTO博客,原文链接:http://blog.51cto.com/06peng/962490,如需转载请自行联系原作者