这段代码用于从android手机向服务器上传图片文件,非FTP方式,当然稍作修改就可以用于上传其它文件。各位看官可以根据自己需要进行适当修改。不足之处还请指出,谢谢!

/**
 * upload file by making a form and return whether file upload successfuly
 *
 * @author Chen.Zhidong
 * @param params
 * @param dirname
 * @param filename
 * @param link
 * @return boolean whether file upload succeeded or failed
 */
public static boolean fileUpload(Map<string , String> params, String dirname, String filename, String link) {
    try {
        String BOUNDARY = "---";
        String MULTIPART_FORM_DATA = "Multipart/form-data";
        URL url = new URL(link);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setDoInput(true);
        conn.setDoOutput(true);
        conn.setUseCaches(false);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Connection", "Keep-Alive");
        conn.setRequestProperty("Charset", "UTF-8");
        conn.setRequestProperty("Content-Type", MULTIPART_FORM_DATA + ";boundary=" + BOUNDARY);
        DataOutputStream outStream = new DataOutputStream(conn.getOutputStream());
        if (params != null && !params.isEmpty()) {
            StringBuilder sb = new StringBuilder();
            for (Map.Entry</string><string , String> entry : params.entrySet()) {
                sb.append(BOUNDARY);
                sb.append("\r\n");
                sb.append("Content-Disposition: form-data; name=\"" + entry.getKey() + "\"\r\n\r\n");
                sb.append(entry.getValue());
                sb.append("\r\n");
            }
            outStream.write(sb.toString().getBytes());
        }
        //此处用的是我自己写的一个读图片的函数,看官可以改成自己的获取文件到byte[]的函数
        byte[] content = ImageUtil.readImageByte(dirname + '/' + filename);
        StringBuilder split = new StringBuilder();
        split.append(BOUNDARY);
        split.append("\r\n");
        split.append("Content-Disposition: form-data;name=\"imgfile\";filename=\"" + filename + "\"\r\n");
        split.append("Content-Type: image/jpg\r\n");
        outStream.write(split.toString().getBytes());
        outStream.write(content, 0, content.length);
        outStream.write("\r\n".getBytes());
        byte[] end_data = (BOUNDARY + "--\r\n").getBytes();
        outStream.write(end_data);
        outStream.flush();
        if (conn.getInputStream() != null) {
            conn.disconnect();
            return true;
        }
        else {
            conn.disconnect();
        }
    }catch (IOException e) {
        e.printStackTrace();
    }
    return false;
}