gpt4 book ai didi

php - 如果(setChunkedStreamingMode)无法将文件从android发送到php

转载 作者:行者123 更新时间:2023-11-29 01:55:44 51 4
gpt4 key购买 nike

试图将大文件从 android 发送到 php,我可以发送小尺寸(最多 1 mp)我四处寻找解决方案,出现了“setChunkedStreamingMode”当我设置 connection.setconnection(1024) 时,我无法发送任何文件,即使是小文件。获取 PHP 回显“无法上传文件!!!”这是安卓代码

public static void main(String[] args) throws IOException, URISyntaxException {



uploadFileToServer("path","http://"");
downloadFileFromServer("path","http://"");
}

/**
* This function upload the large file to server with other POST values.
* @param filename
* @param targetUrl
* @return
*/
public static String uploadFileToServer(String filename, String targetUrl) {
String response = "error";
HttpURLConnection connection = null;
DataOutputStream outputStream = null;

String pathToOurFile = filename;
String urlServer = targetUrl;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
//String path = filename;
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024;
try {
FileInputStream fileInputStream = new FileInputStream(new File(
pathToOurFile));

URL url = new URL(urlServer);
connection = (HttpURLConnection) url.openConnection();

// Allow Inputs & Outputs
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
//connection.setChunkedStreamingMode(1024);
// Enable POST method
connection.setRequestMethod("POST");
connection.setRequestProperty("uploaded_file", filename);
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("Content-Type",
"multipart/form-data; boundary=" + boundary);


outputStream = new DataOutputStream(connection.getOutputStream());
outputStream.writeBytes(twoHyphens + boundary + lineEnd);

String token = "anyvalye";
outputStream.writeBytes("Content-Disposition: form-data; name=\"Token\"" + lineEnd);
outputStream.writeBytes("Content-Type: text/plain;charset=UTF-8" + lineEnd);
outputStream.writeBytes("Content-Length: " + token.length() + lineEnd);
outputStream.writeBytes(lineEnd);
outputStream.writeBytes(token + lineEnd);
outputStream.writeBytes(twoHyphens + boundary + lineEnd);


String taskId = "anyvalue";
outputStream.writeBytes("Content-Disposition: form-data; name=\"TaskID\"" + lineEnd);
outputStream.writeBytes("Content-Type: text/plain;charset=UTF-8" + lineEnd);
outputStream.writeBytes("Content-Length: " + taskId.length() + lineEnd);
outputStream.writeBytes(lineEnd);
outputStream.writeBytes(taskId + lineEnd);
outputStream.writeBytes(twoHyphens + boundary + lineEnd);

String connstr = null;
connstr = "Content-Disposition: form-data; name=\"uploaded_file\";filename=\""
+ pathToOurFile + "\"" + lineEnd;

outputStream.writeBytes(connstr);
outputStream.writeBytes(lineEnd);

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

// Read file
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
System.out.println("Image length " + bytesAvailable + "");
try {
while (bytesRead > 0) {
try {
outputStream.write(buffer, 0, bufferSize);
} catch (OutOfMemoryError e) {
e.printStackTrace();
response = "outofmemoryerror";
return response;
}
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
} catch (Exception e) {
e.printStackTrace();
response = "error";
return response;
}
outputStream.writeBytes(lineEnd);
outputStream.writeBytes(twoHyphens + boundary + twoHyphens
+ lineEnd);

// Responses from the server (code and message)
int serverResponseCode = connection.getResponseCode();
String serverResponseMessage = connection.getResponseMessage();
System.out.println("Server Response Code " + " " + serverResponseCode);
System.out.println("Server Response Message "+ serverResponseMessage);

if (serverResponseCode == 200) {
response = "true";
}else
{
response = "false";
}

fileInputStream.close();
outputStream.flush();

connection.getInputStream();
//for android InputStream is = connection.getInputStream();
java.io.InputStream is = connection.getInputStream();

int ch;
StringBuffer b = new StringBuffer();
while( ( ch = is.read() ) != -1 ){
b.append( (char)ch );
}

String responseString = b.toString();
System.out.println("response string is" + responseString); //Here is the actual output

outputStream.close();
outputStream = null;

} catch (Exception ex) {
// Exception handling
response = "error";
System.out.println("Send file Exception" + ex.getMessage() + "");
ex.printStackTrace();
}
return response;
}

/**
* This function download the large files from the server
* @param filename
* @param urlString
* @throws MalformedURLException
* @throws IOException
*/
public static void downloadFileFromServer(String filename, String urlString) throws MalformedURLException, IOException
{
BufferedInputStream in = null;
FileOutputStream fout = null;
try
{
URL url = new URL(urlString);

in = new BufferedInputStream(url.openStream());
fout = new FileOutputStream(filename);

byte data[] = new byte[1024];
int count;
while ((count = in.read(data, 0, 1024)) != -1)
{
fout.write(data, 0, count);
System.out.println(count);
}
}
finally
{
if (in != null)
in.close();
if (fout != null)
fout.close();
}
System.out.println("Done");
}

这是PHP代码

<?php
$target_path = "uploads/";
/* Add the original filename to our target path.
Result is "uploads/filename.extension" */
$target_path = $target_path . basename( $_FILES['uploaded_file']['name']);
if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $target_path)) {
echo "The first file ". basename( $_FILES['uploaded_file']['name']).
" uploaded.";
} else{
echo "cannot uploading the file!!!! ";
echo "filename: " . basename( $_FILES['uploaded_file']['name']);
echo "target_path: " .$target_path;
}
?>

有什么帮助吗?谢谢

最佳答案

**使用此 PHP 代码,它对我来说工作正常 **

public void uploadFile() {
String charset = "UTF-8";
File[] uploadFileArray = new File[mediaList.size()];

for (int i = 0; i < mediaList.size(); i++) {
uploadFileArray[i] = new File(mediaList.get(i).getMediaPath());
}

try {
MultipartUtility multipart = new MultipartUtility(upLoadServerUri, charset);

for (int i = 0; i < mediaList.size(); i++) {
if (isImage)) {
multipart.addFilePart("image_doc[]", uploadFileArray[i]);
}
else if (isVideo) {
multipart.addFilePart("video_doc[]", uploadFileArray[i]);
}
else if (isAudio) {
multipart.addFilePart("audio_doc[]", uploadFileArray[i]);
}
}

List<String> responseUploadDocument = multipart.finish();
System.out.println("SERVER REPLIED:");

for (String line : responseUploadDocument) {
System.out.println(line);
responseUploadDocumentString = line;
}

if (responseUploadDocumentString != null) {
JSONObject jsonObj = new JSONObject(responseUploadDocumentString);
statusUploadDoc = jsonObj.getString("status");
}

} catch (Exception e) {
e.printStackTrace();
}

关于php - 如果(setChunkedStreamingMode)无法将文件从android发送到php,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15273380/

51 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com