首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >安卓:如何上传.mp3文件到http服务器?

安卓:如何上传.mp3文件到http服务器?
EN

Stack Overflow用户
提问于 2011-02-11 16:20:32
回答 3查看 43.5K关注 0票数 19

我想将.mp3文件(仅)从设备上传到我的服务器。

我想浏览媒体数据的路径,选择任意mp3文件并上传。

我该怎么做呢?

EN

回答 3

Stack Overflow用户

发布于 2011-05-24 02:12:43

谢谢你的好建议,基顿。

我对Java代码进行了一些调整,以便随时可以使用并添加对其他URL参数的支持:

public class HttpMultipartUpload {
    static String lineEnd = "\r\n";
    static String twoHyphens = "--";
    static String boundary = "AaB03x87yxdkjnxvi7";

    public static String upload(URL url, File file, String fileParameterName, HashMap<String, String> parameters)
            throws IOException {
        HttpURLConnection conn = null;
        DataOutputStream dos = null;
        DataInputStream dis = null;
        FileInputStream fileInputStream = null;

        byte[] buffer;
        int maxBufferSize = 20 * 1024;
        try {
            //------------------ CLIENT REQUEST
            fileInputStream = new FileInputStream(file);

            // open a URL connection to the Servlet
            // Open a HTTP connection to the URL
            conn = (HttpURLConnection) url.openConnection();
            // 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("Content-Type", "multipart/form-data;boundary=" + boundary);

            dos = new DataOutputStream(conn.getOutputStream());

            dos.writeBytes(twoHyphens + boundary + lineEnd);
            dos.writeBytes("Content-Disposition: form-data; name=\"" + fileParameterName
                    + "\"; filename=\"" + file.toString() + "\"" + lineEnd);
            dos.writeBytes("Content-Type: text/xml" + lineEnd);
            dos.writeBytes(lineEnd);

            // create a buffer of maximum size
            buffer = new byte[Math.min((int) file.length(), maxBufferSize)];
            int length;
            // read file and write it into form...
            while ((length = fileInputStream.read(buffer)) != -1) {
                dos.write(buffer, 0, length);
            }

            for (String name : parameters.keySet()) {
                dos.writeBytes(lineEnd);
                dos.writeBytes(twoHyphens + boundary + lineEnd);
                dos.writeBytes("Content-Disposition: form-data; name=\"" + name + "\"" + lineEnd);
                dos.writeBytes(lineEnd);
                dos.writeBytes(parameters.get(name));
            }

            // send multipart form data necessary after file data...
            dos.writeBytes(lineEnd);
            dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
            dos.flush();
        } finally {
            if (fileInputStream != null) fileInputStream.close();
            if (dos != null) dos.close();
        }

        //------------------ read the SERVER RESPONSE
        try {
            dis = new DataInputStream(conn.getInputStream());
            StringBuilder response = new StringBuilder();

            String line;
            while ((line = dis.readLine()) != null) {
                response.append(line).append('\n');
            }

            return response.toString();
        } finally {
            if (dis != null) dis.close();
        }
    }
}
票数 6
EN

Stack Overflow用户

发布于 2014-05-06 16:39:11

请注意,如果你复制并粘贴上面的PHP代码,任何人都可以上传一个恶意的PHP脚本到你的服务器上并运行它,时刻注意这一点,用PHP检查扩展服务器端有成千上万的例子在这里和在网络上如何做到这一点。此外,为了获得更高的安全性,将规则添加到apache、nginx服务器以添加标题Content-Disposition (jpg、png、gif、?)并且不解析上传文件夹中的PHP代码。

例如,在nxgin中,它可能是这样的…

#add header Content-Disposition
location ^~ /upload/pictures {

        default_type application/octet-stream;

    types {
            image/gif     gif;
            image/jpeg    jpg;
            image/png    png;
    }

    add_header X-Content-Type-Options 'nosniff';

    if ($request_filename ~ /(((?!\.(jpg)|(png)|(gif)$)[^/])+$)) {
        add_header Content-Disposition 'attachment; filename="$1"';
            # Add X-Content-Type-Options again, as using add_header in a new context
            # dismisses all previous add_header calls:
            add_header X-Content-Type-Options 'nosniff';
        }
}

#do NOT parse PHP script on the upload folder
location ~ \.php$ {
    try_files $uri =404;
    include /etc/nginx/fastcgi_params;
    #if is the upload folder DO NOT parse PHP scripts on it
    if ($uri !~ "^/upload/pictures") {
        fastcgi_pass unix:/var/run/php-fastcgi/php-fastcgi.socket;
    }
    fastcgi_index index.php;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
}
票数 1
EN

Stack Overflow用户

发布于 2016-10-08 05:48:59

我知道这个问题被问了好一阵子。在尝试了很多解决方案后,我发现@Keaton的代码可以为我工作,但它阻塞了我的UI (我使用的是Android Studio2.1.2),所以我不得不把它包装在一个AsyncTask中。

所以使用@Keaton的代码,我得到了这样的结果。

从我的onClickListener()

private View.OnClickListener btnUpload = new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        new doFileUpload().execute();
    }
};

然后是AsyncTask

public class doFileUpload extends AsyncTask<Void, Void, Void> {

    @Override
    protected Void doInBackground(Void... params) {

        <Keaton's code>

     return null;
   }
}

我希望这对有同样问题的人有所帮助。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/4966910

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档