简体   繁体   English

无法将文件上传到Web服务

[英]Failed to upload a file to web service

I have a web service that get a audio and do some operation on it and finally returns a string ,this web service have a web page like this 我有一个Web服务,该服务获取音频并对其进行一些操作,最后返回一个字符串,该Web服务具有这样的网页

<form name="form1" method="post" action="Default.aspx" id="form1" enctype="multipart/form-data">

<input type="file" name="FileUpload3" id="FileUpload3" style="width:325px;" />
<input type="submit" name="Button6" value="Upload File" id="Button6" />   
<span id="Label1"></span>

</form>

when file choose for uploadfile3 and press upload file a same page should be reload and then show the string in span lable, I want to connect this web service by android so I tried below code to connect and upload file, the server response 200 code but no file uploads to server and no string shows, it seems that server press upload file without choosing file, what can I do? 当文件选择为uploadfile3并按上载文件时,应重新加载同一页面,然后在跨度标签中显示字符串,我想通过android连接此Web服务,因此我尝试了以下代码来连接和上载文件,服务器响应为200,但是没有文件上传到服务器,也没有显示字符串,服务器似乎没有选择文件就按了上传文件,我该怎么办? help please. 请帮助。

public void upLoad2Server() throws ClientProtocolException, IOException {

    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost("http://11.12.13.174/file_transfer_sample/ClientWebSite/Default.aspx");

    File file = new File(Environment.getExternalStorageDirectory().getPath() + "/test.wav");
    ContentBody cbFile = new FileBody(file, "audio/wav"); 
    MultipartEntity reqEntity = new MultipartEntity();
    reqEntity.addPart("FileUpload3", cbFile);
    httppost.setEntity(reqEntity);  
    HttpResponse response = httpclient.execute(httppost);
    Log.i("status", String.valueOf(response.getStatusLine()));
}

Check this code to upload file from Android to Web Server 检查此代码以将文件从Android上传到Web服务器

public class UploadFileToServer extends AsyncTask<Object, String, Object>
{
URL connectURL;
String params;
String responseString;
String fileName;
byte[] dataToServer;
FileInputStream fileInputStream;
private int serverResponseCode;

private String serverResponseMessage;

private static final String TAG = "Uploader";


public void setUrlAndFile(String urlString, File fileName)
{
    Log.d(TAG,"StartUploader");

    try
    {
        fileInputStream = new FileInputStream(fileName);
        connectURL = new URL(urlString);
    }
    catch(Exception e)
    {
        e.getStackTrace();
        publishProgress(e.toString());

    }
    this.fileName = fileName.getAbsolutePath()+".txt";

}

synchronized void doUpload()
{
    String lineEnd = "\r\n";
    String twoHyphens = "--";
    String boundary = "*****";
    Log.d(TAG,"lv1");

    try
    {
        Log.d(TAG,"doUpload");
        publishProgress("Uploading...");

        HttpURLConnection conn = (HttpURLConnection)connectURL.openConnection();
        conn.setDoInput(true);
        conn.setDoOutput(true);
        conn.setUseCaches(false);
        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=\"Uploaded\";filename=\"" + fileName + "\"" + lineEnd);
        dos.writeBytes(lineEnd);

        Log.d(TAG,"LvA");
        Log.d(TAG,twoHyphens + boundary + lineEnd + ";Content-Disposition:form-data; name=\"Uploaded\";filename=\"" + fileName + "\"" + lineEnd);

        int bytesAvailable = fileInputStream.available();

        int maxBufferSize = 1024;
        int bufferSize = Math.min(bytesAvailable, maxBufferSize);

        byte[] buffer = new byte[bufferSize];

        int bytesRead = fileInputStream.read(buffer,0, bufferSize);
        Log.d(TAG,"LvB");
        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);

        fileInputStream.close();
       dos.flush();

        InputStream is = conn.getInputStream();
        int ch;
        Log.d(TAG,"LvC");
        StringBuffer buff = new StringBuffer();
        while((ch=is.read()) != -1)
        {
            buff.append((char)ch);
        }
       // publishProgress(buff.toString());
        dos.close();


     // Responses from the server (code and message)
        serverResponseCode = conn.getResponseCode();
        serverResponseMessage = conn.getResponseMessage();
       // Log.d(TAG,"Buffer "+buff.toString());

        Log.d(TAG,"Server Response "+serverResponseMessage);
    }

    catch(Exception e)
    {
        e.getStackTrace();
       publishProgress(e.toString());
    }
}

@Override
protected Object doInBackground(Object... arg0) 
{
    Log.d(TAG,"lv1a");
    doUpload();
    Log.d(TAG,"Uploading Completed! Path: "+connectURL);

    return null;
}

protected void onProgressUpdate(String... progress)
{
    //this.info.setText(progress[0]);
    Log.d("Progress", progress[0]);
}


}

Thanks 谢谢

Check this code.It's upload a file to .NET httphandler server. 检查此代码,它将文件上传到.NET httphandler服务器。 It uses SSL self-signed security, but it's an example how to use methods, and multipart entity. 它使用SSL自签名安全性,但这是如何使用方法和多部分实体的示例。 It works for me. 这个对我有用。

public static void main(String[] args) throws IOException {
    try {
         File f = new File(
                "c:\\eula.1028.txt");

         System.out.println("LENGTH " + f.length());        
         PostMethod method = new PostMethod("/Handler");            
         FilePart filePart = new FilePart("file",f);
         filePart.setContentType("application/pdf");
         Part[] parts = {filePart};
         MultipartRequestEntity request = new
         MultipartRequestEntity(parts, method.getParams());
         method.setRequestEntity(request);

        Protocol easyhttps = new Protocol("https",
                new EasySSLProtocolSocketFactory(), 2000);
        org.apache.commons.httpclient.HttpClient client = new org.apache.commons.httpclient.HttpClient();
        client.getHostConfiguration().setHost("localhost", 2000, easyhttps);

        client.executeMethod(method);
        String s = method.getResponseBodyAsString();
        System.out.println(s);
    } catch (Exception e) {
        System.out.println(e.getMessage());
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM