отправка дополнительных параметров сообщения на сервер в Android при загрузке файла

php android

71 просмотра

1 ответ

У меня есть этот код

connection.setRequestMethod("POST");

    connection.setRequestProperty("Connection", "Keep-Alive");
    connection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);

    outputStream = new DataOutputStream(connection.getOutputStream());
    outputStream.writeBytes(twoHyphens + boundary + lineEnd);
    outputStream.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + pathToOurFile  +"\"" + lineEnd);
    outputStream.writeBytes(lineEnd);

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

Я использую этот код для сохранения файла на моем php-сервере, мне нужно добавить, POSTнапример call=sendfile, дополнительный параметр , чтобы я мог прочитать его в php следующим образом:

<?php
   require "conn.php";
   require "helper.php";
   $call = $_POST["call"]; // this should return sendfile
   if($_FILES["uploadedfile"]["name"]) {
   .....
   }
 ?>

Как я могу достичь этого?

Автор: Sora Источник Размещён: 08.11.2019 11:07

Ответы (1)


0 плюса

Используйте этот класс

public class FileUploader {
private static final String LINE_FEED = "\r\n";
private final String boundary;
private HttpsURLConnection httpConn;
private String charset;
private OutputStream outputStream;
private PrintWriter writer;

public FileUploader(String requestURL)
        throws IOException {
    this.charset = "UTF-8";

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

    URL url = new URL(requestURL);
    httpConn = (HttpsURLConnection) url.openConnection();
    httpConn.setUseCaches(false);
    httpConn.setDoOutput(true); // indicates POST method
    httpConn.setDoInput(true);
    httpConn.setRequestMethod("POST");
    httpConn.setRequestProperty("Content-Type",
            "multipart/form-data; boundary=" + boundary);

    httpConn.setRequestProperty("User-Agent", "CodeJava Agent");
    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("--").append(boundary).append(LINE_FEED);
    writer.append("Content-Disposition: form-data; name=\"").append(name).append("\"")
            .append(LINE_FEED);
    writer.append("Content-Type: text/plain; charset=").append(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("--").append(boundary).append(LINE_FEED);
    writer.append("Content-Disposition: form-data; name=\"").append(fieldName).append("\"; filename=\"").append(fileName).append("\"")
            .append(LINE_FEED);
    writer.append("Content-Type: ").append(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).append(": ").append(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 String finish() {
    String response = "";

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

    // checks server's status code first
    int status = 0;
    try {
        status = httpConn.getResponseCode();

        if (status == HttpsURLConnection.HTTP_OK) {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    httpConn.getInputStream()));
            String line = null;
            while ((line = reader.readLine()) != null) {
                response += line;
            }
            reader.close();
            httpConn.disconnect();
        } else {
            return null;
        }
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }

    return response;
}}

Тогда используйте

FileUploader multipart = new FileUploader(url);

File file = new File("path");
multipart.addFilePart("file", file);

File image = new File("imgPath");
multipart.addFilePart("image", image);

multipart.addFormField("userid", userId);

String response = multipart.finish();
Автор: Sabish.M Размещён: 20.08.2016 09:37
Вопросы из категории :
32x32