Android:在服务器上传文件

时间:2016-03-15 08:36:15

标签: android multipartform-data

PostmanSnapshot

   HttpURLConnection conn = null;
   DataOutputStream dos = null;
   DataInputStream inStream = null;
   String lineEnd = "\r\n";
   String twoHyphens = "--";
   String boundary = "*****";
   int bytesRead, bytesAvailable, bufferSize;
   byte[] buffer;
   int maxBufferSize = 1 * 1024 * 1024;
   try {
    FileInputStream fileInputStream = new FileInputStream(new File(selectedPath));
    URL url = new URL(UPLOAD_URL);
    conn = (HttpURLConnection) url.openConnection();
    conn.setDoInput(true);
    conn.setDoOutput(true);
    conn.setRequestMethod("POST");
    conn.setRequestProperty("authToken", authToken);
    conn.setRequestProperty("Connection", "Keep-Alive");
    conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);

    dos = new DataOutputStream(conn.getOutputStream());
    dos.writeBytes(lineEnd+twoHyphens + boundary + lineEnd);
    dos.writeBytes("Content-Disposition: form-data; name:\"photo-0\";filename=\"" + selectedPath + "\"" + lineEnd);
    dos.writeBytes("Content-Type: multipart/form-data"+lineEnd+lineEnd);
    dos.writeBytes(lineEnd);
    bytesAvailable = fileInputStream.available();
    bufferSize = Math.min(bytesAvailable, maxBufferSize);
    buffer = new byte[bufferSize];

    bytesRead = bytesAvailable;

    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();
    dos.close();

    } catch (MalformedURLException ex) {
    Log.e("Debug", "error: " + ex.getMessage(), ex);
    } catch (IOException ioe) {
    Log.e("Debug", "error: " + ioe.getMessage(), ioe);
    }
    try {
    inStream = new DataInputStream ( conn.getInputStream() );
    String str;

    while (( str = inStream.readLine()) != null)
    {
    Log.e("Debug","Server Response "+str);
    }
    inStream.close();

    }
    catch (IOException ioex){
    Log.e("Debug", "error: " + ioex.getMessage(), ioex);
    }

此代码用于从Android应用程序上传服务器上的文件。 运行代码时服务器状态为true,但不通过服务器发送文件。 我附上了邮差快照。授权代码在标题中发送。

请帮忙

1 个答案:

答案 0 :(得分:1)

我找到了一些可能有助于寻找同样问题的人。 这是工作。我做错了是在while循环中。

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;

public MultipartUtility(String requestURL, String charset)
        throws IOException {
    this.charset = charset;
    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.setConnectTimeout(10000);//10 sec timeout
    httpConn.setRequestProperty("Content-Type","multipart/form-data;      boundary=" + boundary);
    httpConn.setRequestProperty("authToken", LoginActivity.authenticationToken);
    outputStream = httpConn.getOutputStream();
    writer = new PrintWriter(new OutputStreamWriter(outputStream, charset), true);
}

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();
}

public String finish() throws IOException {
    StringBuilder sb = new StringBuilder();
    writer.append(LINE_FEED).flush();
    writer.append("--" + boundary + "--").append(LINE_FEED);
    writer.close();
    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) {
            sb.append(line + "\n");
        }
        reader.close();
        httpConn.disconnect();
    } else {
        throw new IOException("Server returned non-OK status: " + status);
    }
    return sb.toString();
}

}