Android nt处理:表单数据;名称=\“”+字段名 + "\"; 文件名=\“”+文件名+\“”) .append(换行符); writer.append( “内容类型:” +URLConnection.guessContentTypeFromName(文件名)) .append(换行符); writer.append(“内容传输编码:二进制”).append(换行符); writer.append(换行符); writer.flush(); FileInputStream inputStream=新的FileInputStream(上传文件); 字节[]缓冲区=新字节[4096]; int字节读取=-1; 而((bytesRead=inputStream.read(缓冲区))!=-1){ 写入(缓冲区,0,字节读取); } outputStream.flush(); inputStream.close(); writer.append(换行符); writer.flush(); } /** *向请求添加标题字段。 * *@param name-标题字段的名称 *@param value-标题字段的值 */ public void addHeaderField(字符串名称、字符串值){ writer.append(name+”:“+value).append(LINE\u FEED); writer.flush(); } /** *完成请求并从服务器接收响应。 * *@返回字符串列表作为服务器返回时的响应 *状态为OK,否则将引发异常。 *@抛出异常 */ public List finish()引发IOException{ 列表响应=新建ArrayList(); writer.append(LINE_FEED.flush(); writer.append(“-”+边界+“-”).append(换行符); writer.close(); //首先检查服务器的状态代码 int status=httpConn.getResponseCode(); if(status==HttpURLConnection.HTTP\u OK){ BufferedReader reader=新的BufferedReader(新的InputStreamReader( httpConn.getInputStream()); 字符串行=null; 而((line=reader.readLine())!=null){ 响应。添加(行); } reader.close(); httpConn.disconnect(); }否则{ 抛出新IOException(“服务器返回非OK状态:+状态”); } 返回响应; } }

Android nt处理:表单数据;名称=\“”+字段名 + "\"; 文件名=\“”+文件名+\“”) .append(换行符); writer.append( “内容类型:” +URLConnection.guessContentTypeFromName(文件名)) .append(换行符); writer.append(“内容传输编码:二进制”).append(换行符); writer.append(换行符); writer.flush(); FileInputStream inputStream=新的FileInputStream(上传文件); 字节[]缓冲区=新字节[4096]; int字节读取=-1; 而((bytesRead=inputStream.read(缓冲区))!=-1){ 写入(缓冲区,0,字节读取); } outputStream.flush(); inputStream.close(); writer.append(换行符); writer.flush(); } /** *向请求添加标题字段。 * *@param name-标题字段的名称 *@param value-标题字段的值 */ public void addHeaderField(字符串名称、字符串值){ writer.append(name+”:“+value).append(LINE\u FEED); writer.flush(); } /** *完成请求并从服务器接收响应。 * *@返回字符串列表作为服务器返回时的响应 *状态为OK,否则将引发异常。 *@抛出异常 */ public List finish()引发IOException{ 列表响应=新建ArrayList(); writer.append(LINE_FEED.flush(); writer.append(“-”+边界+“-”).append(换行符); writer.close(); //首先检查服务器的状态代码 int status=httpConn.getResponseCode(); if(status==HttpURLConnection.HTTP\u OK){ BufferedReader reader=新的BufferedReader(新的InputStreamReader( httpConn.getInputStream()); 字符串行=null; 而((line=reader.readLine())!=null){ 响应。添加(行); } reader.close(); httpConn.disconnect(); }否则{ 抛出新IOException(“服务器返回非OK状态:+状态”); } 返回响应; } },android,file-upload,httpclient,multipart,Android,File Upload,Httpclient,Multipart,用法 private void uploadMedia(){ 试一试{ 字符串charset=“UTF-8”; File uploadFile1=新文件(“/sdcard/myvideo.mp4”); String requestURL=Data.BASE\u URL+Data.URL\u UPLOAD\u REACTION\u TEST; multipartity multipart=新的multipartity(请求URL,字符集); //addHeaderField(“用户代理”、“代码J

用法

private void uploadMedia(){
试一试{
字符串charset=“UTF-8”;
File uploadFile1=新文件(“/sdcard/myvideo.mp4”);
String requestURL=Data.BASE\u URL+Data.URL\u UPLOAD\u REACTION\u TEST;
multipartity multipart=新的multipartity(请求URL,字符集);
//addHeaderField(“用户代理”、“代码Java”);
//多部分addHeaderField(“测试标头”、“标头值”);
多部分addFormField(“朋友id”,“酷图片”);
addFormField(“用户ID”、“Java、upload、Spring”);
multipart.addFilePart(“uploadedfile”,uploadFile1);
列表响应=multipart.finish();
Log.v(“rht”,“服务器回复:”);
for(字符串行:响应){
对数v(“rht”,“行:”+行);
}
}捕获(例外e){
e、 printStackTrace();
}
}
接受上传的PHP代码

<?php

    $friend_id = $_REQUEST['friend_id'];
    $userid = $_REQUEST['userid'];

    echo 'friend_id : '.$friend_id. ' userid '.$userid;

    move_uploaded_file($_FILES['uploadedfile']['tmp_name'], "./uploads/".$_FILES["uploadedfile"]["name"]);

?>


你想上传多个大型内容,对吗?我只是clarefyingYes,服务器已经完成了,但在Android中,我们将拍摄一些照片、视频或音频,然后上传到服务器。因此我采用了与我发布的问题解决方案类似的方法。但我必须添加3个库才能“正常工作”“,但我达到了移动到
Android Studio
的极限,希望我能。。。但不在我手中。大老板不想把项目转移到它身上。。(多次试图说服..buuuuutt…不走运)谢谢@ArsalImam我会试试告诉你一些事情只问一个问题,“jsonString”是什么?我的意思是,我不知道从哪里获得它,或者它代表了什么(对不起,在这种类型的服务器中有点新手)。实际上,兄弟,这种方法涵盖了android和服务器之间的主要功能,你可以设置jsonString=”“m。。我被绊倒了。。正在启动此错误:09-10 14:09:28.160:E/AndroidRuntime(11166):java.lang.NoSuchFieldError:没有类型为Lorg/apache/http/message/BasicHeaderValueFormatter的静态字段实例;Lorg/apache/http/message/BasicHeaderValueFormatter类中;或者它的超类(声明'org.apache.http.message.BasicHeaderValueFormatter'出现在/system/framework/ext.jar中)是您正在使用的库问题。。。。!如何在其中添加进度条。。?
// Method for sending files using multiparting......
public static String sendJsonWithFile(Activity mActivity, ArrayList<String> mImagePaths, String jsonString, String URL)
{
    Log.e("json", jsonString);
    String res = "";
    try
    {
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(URL);
        String boundary = "*****" + Long.toString(System.currentTimeMillis()) + "*****";
        boundary = "--" + boundary;
        httppost.addHeader("Content-Type", "multipart/form-data; boundary=" + boundary);
        MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

    StringBody stringBody = new StringBody(jsonString);

    reqEntity.addPart("formstring", stringBody);

    for (int i = 0; i < mImagePaths.size(); i++)
    {
        String imagePath = mImagePaths.get(i);
        if (mImagePaths != null && mImagePaths.size() > 0)
        {

            byte[] filebytes = FileUtils.readFileToByteArray(new File(imagePath));

            ByteArrayBody filebodyImage = new ByteArrayBody(filebytes, "image");
            Log.e("file path=", filebodyImage.toString());

            reqEntity.addPart("image", filebodyImage);

        }

    }

    httppost.setEntity(reqEntity);
    HttpResponse response = httpclient.execute(httppost);
    HttpEntity resEntity = response.getEntity();
    if (resEntity != null)
    {
        res = EntityUtils.toString(resEntity);
        System.out.println(res);
    }

    if (resEntity != null)
    {
        resEntity.consumeContent();
    }
    httpclient.getConnectionManager().shutdown();
}
catch (UnsupportedEncodingException e)
{
    res = "UnsupportedEncodingException";
    e.printStackTrace();
}
catch (ClientProtocolException e)
{
    res = "ClientProtocolException";
    e.printStackTrace();
}
catch (FileNotFoundException e)
{
    res = "FileNotFoundException";
    e.printStackTrace();
}
catch (IOException e)
{
    res = "IOException";
    e.printStackTrace();
}
catch (Exception e)
{
    res = "Exception";
    e.printStackTrace();
}
return res;
}
import java.util.List;

import java.io.BufferedReader;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;

/**
 * This utility class provides an abstraction layer for sending multipart HTTP
 * POST requests to a web server.
 *
 * @author www.codejava.net
 */
public class MultipartUtility {
    private final String boundary;
    private static final String LINE_FEED = "\r\n";
    private HttpURLConnection httpConn;
    private String charset;
    private OutputStream outputStream;
    private PrintWriter writer;

    /**
     * This constructor initializes a new HTTP POST request with content type
     * is set to multipart/form-data
     *
     * @param requestURL
     * @param charset
     * @throws IOException
     */
    public MultipartUtility(String requestURL, String charset)
            throws IOException {
        this.charset = charset;

        // creates a unique boundary based on time stamp
        boundary = "===" + System.currentTimeMillis() + "===";

        URL url = new URL(requestURL);
        httpConn = (HttpURLConnection) url.openConnection();
        httpConn.setUseCaches(false);
        httpConn.setDoOutput(true); // indicates POST method
        httpConn.setDoInput(true);
        httpConn.setRequestProperty("Content-Type",
                "multipart/form-data; boundary=" + boundary);
        httpConn.setRequestProperty("User-Agent", "CodeJava Agent");
        httpConn.setRequestProperty("Test", "Bonjour");
        outputStream = httpConn.getOutputStream();
        writer = new PrintWriter(new OutputStreamWriter(outputStream, charset),
                true);
    }

    /**
     * Adds a form field to the request
     *
     * @param name  field name
     * @param value field value
     */
    public void addFormField(String name, String value) {
        writer.append("--" + boundary).append(LINE_FEED);
        writer.append("Content-Disposition: form-data; name=\"" + name + "\"")
                .append(LINE_FEED);
        writer.append("Content-Type: text/plain; charset=" + charset).append(
                LINE_FEED);
        writer.append(LINE_FEED);
        writer.append(value).append(LINE_FEED);
        writer.flush();
    }

    /**
     * Adds a upload file section to the request
     *
     * @param fieldName  name attribute in <input type="file" name="..." />
     * @param uploadFile a File to be uploaded
     * @throws IOException
     */
    public void addFilePart(String fieldName, File uploadFile)
            throws IOException {
        String fileName = uploadFile.getName();
        writer.append("--" + boundary).append(LINE_FEED);
        writer.append(
                "Content-Disposition: form-data; name=\"" + fieldName
                        + "\"; filename=\"" + fileName + "\"")
                .append(LINE_FEED);
        writer.append(
                "Content-Type: "
                        + URLConnection.guessContentTypeFromName(fileName))
                .append(LINE_FEED);
        writer.append("Content-Transfer-Encoding: binary").append(LINE_FEED);
        writer.append(LINE_FEED);
        writer.flush();

        FileInputStream inputStream = new FileInputStream(uploadFile);
        byte[] buffer = new byte[4096];
        int bytesRead = -1;
        while ((bytesRead = inputStream.read(buffer)) != -1) {
            outputStream.write(buffer, 0, bytesRead);
        }
        outputStream.flush();
        inputStream.close();

        writer.append(LINE_FEED);
        writer.flush();
    }

    /**
     * Adds a header field to the request.
     *
     * @param name  - name of the header field
     * @param value - value of the header field
     */
    public void addHeaderField(String name, String value) {
        writer.append(name + ": " + value).append(LINE_FEED);
        writer.flush();
    }

    /**
     * Completes the request and receives response from the server.
     *
     * @return a list of Strings as response in case the server returned
     * status OK, otherwise an exception is thrown.
     * @throws IOException
     */
    public List<String> finish() throws IOException {
        List<String> response = new ArrayList<String>();

        writer.append(LINE_FEED).flush();
        writer.append("--" + boundary + "--").append(LINE_FEED);
        writer.close();

        // checks server's status code first
        int status = httpConn.getResponseCode();
        if (status == HttpURLConnection.HTTP_OK) {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    httpConn.getInputStream()));
            String line = null;
            while ((line = reader.readLine()) != null) {
                response.add(line);
            }
            reader.close();
            httpConn.disconnect();
        } else {
            throw new IOException("Server returned non-OK status: " + status);
        }

        return response;
    }
}
private void uploadMedia() {
        try {

            String charset = "UTF-8";
            File uploadFile1 = new File("/sdcard/myvideo.mp4");
            String requestURL = Data.BASE_URL+Data.URL_UPLOAD_REACTION_TEST;

            MultipartUtility multipart = new MultipartUtility(requestURL, charset);

//            multipart.addHeaderField("User-Agent", "CodeJava");
//            multipart.addHeaderField("Test-Header", "Header-Value");

            multipart.addFormField("friend_id", "Cool Pictures");
            multipart.addFormField("userid", "Java,upload,Spring");

            multipart.addFilePart("uploadedfile", uploadFile1);

            List<String> response = multipart.finish();

            Log.v("rht", "SERVER REPLIED:");

            for (String line : response) {
                Log.v("rht", "Line : "+line);

            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
<?php

    $friend_id = $_REQUEST['friend_id'];
    $userid = $_REQUEST['userid'];

    echo 'friend_id : '.$friend_id. ' userid '.$userid;

    move_uploaded_file($_FILES['uploadedfile']['tmp_name'], "./uploads/".$_FILES["uploadedfile"]["name"]);

?>