android实现的文件上传案例探讨

来源:互联网 发布:ipad版淘宝怎么看直播 编辑:程序博客网 时间:2024/05/21 06:37

以为要做android项目的文件上传,在CSDN看到了鸿洋_大神的《从原理角度解析Android (Java) http 文件上传》http://blog.csdn.net/lmj623565791/article/details/23781773


从原理角度解析Android (Java) http 文件上传

已经讲的很详细,但是唯一不足的是,提供的源码是Java版本的,然后我又实现了一个android版本的文件上传


下面是主要代码:

/** * Create a thread to upload the file. * @param filepath * @param uploadUrl */public void startUploadFile(final String filepath, final String uploadUrl) {final Message msg = Message.obtain(); // Get the Message object// Create a new thread to do the uploadThread thread = new Thread(new Runnable() {@Overridepublic void run() {// TODO Auto-generated method stubboolean flag = uploadFile(filepath, uploadUrl); // Call the upload file functionif(flag) {msg.what = 1; // Upload file succeeded.} else {msg.what = 0; // Upload file failed.}handler.sendMessage(msg);}});thread.start(); // Start the thread}/** * Upload the specified file to remote server. * @param filepath The path of the local file. * @param uploadUrl The server url. * @return The upload status. */public boolean uploadFile(String filepath, String uploadUrl) {boolean status = true;String end = "\r\n";String twoHyphens = "--";String boundary = "******";try{URL url = new URL(uploadUrl);HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();// Set the size of the transfer stream, in case that the application// collapses due to small memory, this method is used when we don't// know the size of the content, we use HTTP request without cachehttpURLConnection.setChunkedStreamingMode(128 * 1024);// 128K  // Set the input and outputhttpURLConnection.setDoInput(true);httpURLConnection.setDoOutput(true);httpURLConnection.setUseCaches(false);// Set the HTTP methodhttpURLConnection.setRequestMethod("POST");httpURLConnection.setRequestProperty("Connection", "Keep-Alive");httpURLConnection.setRequestProperty("Charset", "UTF-8");httpURLConnection.setRequestProperty("Content-Type","multipart/form-data;boundary=" + boundary);// Get outputstream according to the url connectionDataOutputStream dos = new DataOutputStream(httpURLConnection.getOutputStream());// Write the HTTP POST headerdos.writeBytes(twoHyphens + boundary + end);dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\"; filename=\""+ filepath.substring(filepath.lastIndexOf("/") + 1)                + "\"" + end);            dos.writeBytes(end);                    FileInputStream fis = new FileInputStream(filepath);                        int bufferSize = 8 * 1024; // The size of the buffer, 8KB.            byte[] buffer = new byte[bufferSize];            int length = 0;            while ((length = fis.read(buffer)) != -1) {                        // Write data to DataOutputStream            dos.write(buffer, 0, length);            }                        dos.writeBytes(end);            dos.writeBytes(twoHyphens + boundary + twoHyphens + end);                        fis.close(); // Close the FileInputStream.            dos.flush(); // Flush the data to DataOutputStream.                    // Get the content of the response            InputStream is = httpURLConnection.getInputStream();                        InputStreamReader isr = new InputStreamReader(is, "utf-8");              BufferedReader br = new BufferedReader(isr, 8 * 1024);              String result = br.readLine();                    Log.d(Tag, result);            //            dos.close(); // Will respond I/O exception if closes.          } catch (Exception e) {          e.printStackTrace();          status = true;          }return status;}

private static final String BOUNDARY = "----WebKitFormBoundaryT1HoybnYeFOGFlBR";/** *  * @param params *            传递的普通参数 * @param uploadFile *            需要上传的文件名 * @param fileFormName *            需要上传文件表单中的名字 * @param newFileName *            上传的文件名称,不填写将为uploadFile的名称 * @param urlStr *            上传的服务器的路径 * @throws IOException */public void uploadForm(Map<String, String> params, String fileFormName,File uploadFile, String newFileName, String urlStr)throws IOException {if (newFileName == null || newFileName.trim().equals("")) {newFileName = uploadFile.getName();}StringBuilder sb = new StringBuilder();/** * 普通的表单数据 */for (String key : params.keySet()) {sb.append("--" + BOUNDARY + "\r\n");sb.append("Content-Disposition: form-data; name=\"" + key + "\""+ "\r\n");sb.append("\r\n");sb.append(params.get(key) + "\r\n");}/** * 上传文件的头 */sb.append("--" + BOUNDARY + "\r\n");sb.append("Content-Disposition: form-data; name=\"" + fileFormName+ "\"; filename=\"" + newFileName + "\"" + "\r\n");sb.append("Content-Type: image/jpeg" + "\r\n");// 如果服务器端有文件类型的校验,必须明确指定ContentTypesb.append("\r\n");byte[] headerInfo = sb.toString().getBytes("UTF-8");byte[] endInfo = ("\r\n--" + BOUNDARY + "--\r\n").getBytes("UTF-8");System.out.println(sb.toString());URL url = new URL(urlStr);HttpURLConnection conn = (HttpURLConnection) url.openConnection();conn.setRequestMethod("POST");conn.setRequestProperty("Content-Type","multipart/form-data; boundary=" + BOUNDARY);conn.setRequestProperty("Content-Length", String.valueOf(headerInfo.length + uploadFile.length()+ endInfo.length));conn.setDoOutput(true);OutputStream out = conn.getOutputStream();InputStream in = new FileInputStream(uploadFile);out.write(headerInfo);byte[] buf = new byte[1024];int len;while ((len = in.read(buf)) != -1)out.write(buf, 0, len);out.write(endInfo);in.close();out.close();if (conn.getResponseCode() == 200) {System.out.println("上传成功");}}


0 0
原创粉丝点击