php – 使用HttpURLConnection上传多个图像文件

前端之家收集整理的这篇文章主要介绍了php – 使用HttpURLConnection上传多个图像文件前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想使用HttpURLConnection上传多个图像文件,并且图像数量不固定到从 android上传文件数量.

请不要发送MultiPartEntity的链接.我只想使用HttpURLConnection完成此操作,并且不希望使用任何其他外部库来上传文件.

我想使用HTTPUrlConnection上传文件,例如请参阅此链接

http://www.17od.com/2010/02/18/multipart-form-upload-on-android/

这是我希望上传多个单个文件上传代码

请以PHP脚本为例.

是的,我终于得到了答案.

在android方面.

Fileuploader.java

  1. public class FileUploader {
  2. private final String boundary;
  3. private static final String LINE_Feed = "\r\n";
  4. private HttpURLConnection httpConn;
  5. private String charset;
  6. private OutputStream outputStream;
  7. private PrintWriter writer;
  8.  
  9. public FileUploader(String requestURL,String charset)
  10. throws IOException {
  11. this.charset = charset;
  12.  
  13. // creates a unique boundary based on time stamp
  14. boundary = "===" + System.currentTimeMillis() + "===";
  15.  
  16. URL url = new URL(requestURL);
  17. httpConn = (HttpURLConnection) url.openConnection();
  18. httpConn.setUseCaches(false);
  19. httpConn.setDoOutput(true); // indicates POST method
  20. httpConn.setDoInput(true);
  21. httpConn.setRequestProperty("Content-Type","multipart/form-data; boundary=" + boundary);
  22. httpConn.setRequestProperty("User-Agent","CodeJava Agent");
  23. httpConn.setRequestProperty("Test","Bonjour");
  24. outputStream = httpConn.getOutputStream();
  25. writer = new PrintWriter(new OutputStreamWriter(outputStream,charset),true);
  26. }
  27.  
  28. /**
  29. * Adds a form field to the request
  30. * @param name field name
  31. * @param value field value
  32. */
  33. public void addFormField(String name,String value) {
  34. writer.append("--" + boundary).append(LINE_Feed);
  35. writer.append("Content-Disposition: form-data; name=\"" + name + "\"")
  36. .append(LINE_Feed);
  37. writer.append("Content-Type: text/plain; charset=" + charset).append(
  38. LINE_Feed);
  39. writer.append(LINE_Feed);
  40. writer.append(value).append(LINE_Feed);
  41. writer.flush();
  42. }
  43.  
  44. /**
  45. * Adds a upload file section to the request
  46. * @param fieldName name attribute in <input type="file" name="..." />
  47. * @param uploadFile a File to be uploaded
  48. * @throws IOException
  49. */
  50. public void addFilePart(String fieldName,File uploadFile)
  51. throws IOException {
  52. String fileName = uploadFile.getName();
  53. writer.append("--" + boundary).append(LINE_Feed);
  54. writer.append(
  55. "Content-Disposition: form-data; name=\"" + fieldName
  56. + "\"; filename=\"" + fileName + "\"")
  57. .append(LINE_Feed);
  58. writer.append(
  59. "Content-Type: "
  60. + URLConnection.guessContentTypeFromName(fileName))
  61. .append(LINE_Feed);
  62. writer.append("Content-Transfer-Encoding: binary").append(LINE_Feed);
  63. writer.append(LINE_Feed);
  64. writer.flush();
  65.  
  66. FileInputStream inputStream = new FileInputStream(uploadFile);
  67. byte[] buffer = new byte[4096];
  68. int bytesRead = -1;
  69. while ((bytesRead = inputStream.read(buffer)) != -1) {
  70. outputStream.write(buffer,bytesRead);
  71. }
  72. outputStream.flush();
  73. inputStream.close();
  74.  
  75. writer.append(LINE_Feed);
  76. writer.flush();
  77. }
  78.  
  79. /**
  80. * Adds a header field to the request.
  81. * @param name - name of the header field
  82. * @param value - value of the header field
  83. */
  84. public void addHeaderField(String name,String value) {
  85. writer.append(name + ": " + value).append(LINE_Feed);
  86. writer.flush();
  87. }
  88.  
  89. /**
  90. * Completes the request and receives response from the server.
  91. * @return a list of Strings as response in case the server returned
  92. * status OK,otherwise an exception is thrown.
  93. * @throws IOException
  94. */
  95. public List<String> finish() throws IOException {
  96. List<String> response = new ArrayList<String>();
  97.  
  98. writer.append(LINE_Feed).flush();
  99. writer.append("--" + boundary + "--").append(LINE_Feed);
  100. writer.close();
  101.  
  102. // checks server's status code first
  103. int status = httpConn.getResponseCode();
  104. if (status == HttpURLConnection.HTTP_OK) {
  105. BufferedReader reader = new BufferedReader(new InputStreamReader(
  106. httpConn.getInputStream()));
  107. String line = null;
  108. while ((line = reader.readLine()) != null) {
  109. response.add(line);
  110. }
  111. reader.close();
  112. httpConn.disconnect();
  113. } else {
  114. throw new IOException("Server returned non-OK status: " + status);
  115. }
  116.  
  117. return response;
  118. }
  119. }

On mainactivity file

在mainactivity.java上只调用这个函数,而imgPaths是图像路径的数组.

  1. public void uploadFile(ArrayList<String> imgPaths) {
  2.  
  3. String charset = "UTF-8";
  4. //File uploadFile1 = new File("e:/Test/PIC1.JPG");
  5. //File uploadFile2 = new File("e:/Test/PIC2.JPG");
  6.  
  7. File sourceFile[] = new File[imgPaths.size()];
  8. for (int i=0;i<imgPaths.size();i++){
  9. sourceFile[i] = new File(imgPaths.get(i));
  10. // Toast.makeText(getApplicationContext(),imgPaths.get(i),Toast.LENGTH_SHORT).show();
  11. }
  12.  
  13. String requestURL = "your API";
  14.  
  15. try {
  16. FileUploader multipart = new FileUploader(requestURL,charset);
  17.  
  18. multipart.addHeaderField("User-Agent","CodeJava");
  19. multipart.addHeaderField("Test-Header","Header-Value");
  20.  
  21. multipart.addFormField("description","Cool Pictures");
  22. multipart.addFormField("keywords","Java,upload,Spring");
  23.  
  24. for (int i=0;i<imgPaths.size();i++){
  25. multipart.addFilePart("uploaded_file[]",sourceFile[i]);
  26. }
  27.  
  28. /*multipart.addFilePart("fileUpload",uploadFile1);
  29. multipart.addFilePart("fileUpload",uploadFile2);*/
  30.  
  31. List<String> response = multipart.finish();
  32.  
  33. System.out.println("SERVER REPLIED:");
  34.  
  35. for (String line : response) {
  36. System.out.println(line);
  37. }
  38. } catch (IOException ex) {
  39. System.err.println(ex);
  40. }
  41. }

uploader.PHP

  1. foreach ($_FILES["uploaded_file"]["error"] as $key => $error) {
  2. if ($error == UPLOAD_ERR_OK) {
  3. $tmp_name = $_FILES["uploaded_file"]["tmp_name"][$key];
  4. $name = $_FILES["uploaded_file"]["name"][$key];
  5. $file_path = "../post_uploaded_images/";
  6. $file_path = $file_path . $name;
  7. if(@move_uploaded_file($tmp_name,$file_path))
  8. {
  9. echo "success";
  10.  
  11. } else{
  12.  
  13. echo "fail";
  14. }
  15. }
  16. }

猜你在找的PHP相关文章