2016-08-20 104 views
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时发送额外的POST参数在Android的服务器例如call=sendfile参数,这样我就可以在PHP这样的阅读:

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

我怎样才能做到这一点?

回答

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