【问题标题】:Unable to upload mp3 file from Android app to asp.net backend无法将 mp3 文件从 Android 应用程序上传到 asp.net 后端
【发布时间】:2020-10-22 23:49:00
【问题描述】:

我想将 mp3 文件从 Android 应用程序上传到我的 asp.net 服务器,我在客户端使用这个类

import android.util.Log;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class HttpFileUpload implements Runnable{
    URL connectURL;
    String responseString;
    String Title;
    String Description;
    byte[ ] dataToServer;
    FileInputStream fileInputStream = null;

    public HttpFileUpload(String urlString, String vTitle, String vDesc){
        try{
            connectURL = new URL(urlString);
            Title= vTitle;
            Description = vDesc;
        }catch(Exception ex){
            Log.i("HttpFileUpload","URL Malformatted");
        }
    }

    public void Send_Now(FileInputStream fStream){
        fileInputStream = fStream;
        Sending();
    }

    void Sending(){
        String iFileName = "temp.mp3";
        String lineEnd = "\r\n";
        String twoHyphens = "--";
        String boundary = "*****";
        String Tag="fSnd";
        try
        {
            Log.e(Tag,"Starting Http File Sending to URL");

            // Open a HTTP connection to the URL
            HttpURLConnection conn = (HttpURLConnection)connectURL.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("Connection", "Keep-Alive");

            conn.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);

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

            dos.writeBytes(twoHyphens + boundary + lineEnd);
            dos.writeBytes("Content-Disposition: form-data; name=\"title\""+ lineEnd);
            dos.writeBytes(lineEnd);
            dos.writeBytes(Title);
            dos.writeBytes(lineEnd);
            dos.writeBytes(twoHyphens + boundary + lineEnd);

            dos.writeBytes("Content-Disposition: form-data; name=\"description\""+ lineEnd);
            dos.writeBytes(lineEnd);
            dos.writeBytes(Description);
            dos.writeBytes(lineEnd);
            dos.writeBytes(twoHyphens + boundary + lineEnd);

            dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + iFileName +"\"" + lineEnd);
            dos.writeBytes(lineEnd);

            Log.e(Tag,"Headers are written");

            // create a buffer of maximum size
            int bytesAvailable = fileInputStream.available();

            int maxBufferSize = 1024;
            int bufferSize = Math.min(bytesAvailable, maxBufferSize);
            byte[ ] buffer = new byte[bufferSize];

            // read file and write it into form...
            int bytesRead = fileInputStream.read(buffer, 0, bufferSize);

            while (bytesRead > 0)
            {
                dos.write(buffer, 0, bufferSize);
                bytesAvailable = fileInputStream.available();
                bufferSize = Math.min(bytesAvailable,maxBufferSize);
                bytesRead = fileInputStream.read(buffer, 0,bufferSize);
            }
            dos.writeBytes(lineEnd);
            dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

            // close streams
            fileInputStream.close();

            dos.flush();

            Log.e(Tag,"File Sent, Response: "+String.valueOf(conn.getResponseCode()));

            InputStream is = conn.getInputStream();

            // retrieve the response from server
            int ch;

            StringBuffer b =new StringBuffer();
            while( ( ch = is.read() ) != -1 ){ b.append( (char)ch ); }
            String s=b.toString();
            Log.i("Response",s);
            dos.close();
        }
        catch (MalformedURLException ex)
        {
            Log.e(Tag, "URL error: " + ex.getMessage(), ex);
        }

        catch (IOException ioe)
        {
            Log.e(Tag, "IO error: " + ioe.getMessage(), ioe);
        }
    }

    @Override
    public void run() {
        // TODO Auto-generated method stub
    }
}

然后我像这样使用上面的类

    public void uploadFile(){
    try {
        File appDir = getContext().getExternalFilesDirs(null)[0];
        File file = new File(appDir.getAbsolutePath() + "/Audios");
        if (!file.exists()) {
            file.mkdirs();
        }

        fileName =  appDir.getAbsolutePath() + "/Audios/temp.mp3";
        FileInputStream fstrm = new FileInputStream(fileName);

        // Set your server page url (and the file title/description)
        HttpFileUpload hfu = new HttpFileUpload("http://www.example.com/Fileup.aspx", "my file title","my file description");

        hfu.Send_Now(fstrm);

    } catch (FileNotFoundException e) {
        // Error: File not found
    }
}

这是服务器端的asp.net代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Fileup : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void Page_Init(object sender, EventArgs e)
    {
        string vTitle = "";
        string vDesc = "";
        string FilePath = Server.MapPath("~/files/cur_file.mp3");
        
        if (!string.IsNullOrEmpty(Request.Form["title"]))
        {
            vTitle = Request.Form["title"];
        }
        if (!string.IsNullOrEmpty(Request.Form["description"]))
        {
            vDesc = Request.Form["description"];
        }

        HttpFileCollection MyFileCollection = Request.Files;
        if (MyFileCollection.Count > 0)
        {
            // Save the File
            MyFileCollection[0].SaveAs(FilePath);
        }
    }
}

注意事项:

  • 我向我的客户端应用程序添加了 INTERNET & EXTERNAL STORAGE 权限
  • 客户端到达这一行并返回代码500 Log.e(Tag,"File Sent, Response: "+String.valueOf(conn.getResponseCode()));然后在下一行抛出异常InputStream is = conn.getInputStream();
  • 然后我在我的服务器上的“文件”文件夹中找不到 mp3 文件
  • mp3 文件只有 16 kb
    有什么问题?

【问题讨论】:

    标签: java c# android asp.net file-upload


    【解决方案1】:

    我解决了,文件夹“files”没有写文件的权限,谢谢

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-07-28
      • 2010-09-12
      • 2019-09-23
      • 2019-02-09
      • 1970-01-01
      • 2016-07-25
      • 2019-11-01
      相关资源
      最近更新 更多