我要将图像从SD卡上传到PHP服务器。我已经阅读了很多文章和主题,但我遇到了一些问题......
首先,我使用了该代码:
HttpURLConnection connection = null;
DataOutputStream outputStream = null;
//DataInputStream inputStream = null;
String urlServer = hostName+"Upload";
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
String serverResponseMessage;
//int serverResponseCode;
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1*1024*1024;
try
{
showLog("uploading file: " + file);
FileInputStream fileInputStream = new FileInputStream(new File(pictureFileDir+"/"+file) );
URL url = new URL(urlServer);
connection = (HttpURLConnection) url.openConnection();
// Allow Inputs & Outputs.
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
// Set HTTP method to POST.
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=\"uploaded_file\";filename=\"" + file +"\"" + lineEnd);
outputStream.writeBytes(lineEnd);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// Read file
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0)
{
outputStream.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
outputStream.writeBytes(lineEnd);
outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
// Responses from the server (code and message)
//serverResponseCode = connection.getResponseCode();
serverResponseMessage = connection.getResponseMessage();
showLog("server response: " + serverResponseMessage);
fileInputStream.close();
outputStream.flush();
outputStream.close();
}
catch (Exception ex)
{
ex.printStackTrace();
}
但是服务器响应200 / OK并且目标服务器上没有文件...
在我阅读了关于Multipart的信息之后:
try {
HttpParams params = new BasicHttpParams();
params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
DefaultHttpClient mHttpClient = new DefaultHttpClient(params);
File image = new File(pictureFileDir + "/" + filename);
HttpPost httppost = new HttpPost(hostName+"Upload");
MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
multipartEntity.addPart("Image", new FileBody(image));
httppost.setEntity(multipartEntity);
mHttpClient.execute(httppost, new PhotoUploadResponseHandler());
} catch (Exception e) {
e.printStackTrace();
}
然后我在LogCat中有这样的LOG而没有别的......
06-04 06:50:52.277:D / dalvikvm(1584):DexOpt:找不到静态字段Lorg / apache / http / message / BasicHeaderValueParser; .INSTANCE 06-04 06:50:52.277:W / dalvikvm(1584):VFY:无法解析Lorg / apache / http / message / BasicHeaderValueParser中的静态字段6688(INSTANCE); 06-04 06:50:52.277:D / dalvikvm(1584):VFY:在0x001b处替换操作码0x62
ServerSide脚本:
$target_path = "uploads";
$target_path = $target_path . basename( $_FILES['Image']);
if(move_uploaded_file($_FILES['tmp_name'], $file_path)) {
echo "success";
} else{
echo "fail";
}
为什么呢?上传图片的最简单方法是什么?
答案 0 :(得分:1)
然后,执行此操作:
try {
MultipartEntityBuilder mBuilder = MultipartEntityBuilder.create();
mBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
File file = new File(YOUR_ABSOLUTE_PATH_STRING);
if (!file.exists())
return null;
mBuilder.addPart("mFile", new FileBody(file));
}
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(YOUR_SERVER_URL);
httpPost.setEntity(mBuilder.build());
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
//Reading the response:
InputStream is = httpEntity.getContent();
BufferedReader reader = new BufferedReader(
new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line;
while ((line = reader.readLine()) != null)
sb.append(line + "\n");
is.close();
httpEntity.consumeContent();
//Do something with the string returned: sb.toString()
} catch (Exception e) {}
PHP代码
$fileName = uniqid() . ".png";
if (move_uploaded_file($_FILES["mFile"]["tmp_name"], "uploads/" . $fileName))
return $fileName;
return "";
此代码适用于我,因此如果它对您不起作用 - 请检查您要发送的图像路径,尝试使用其他图像等。
答案 1 :(得分:0)
试试这个,它也使用multipart,它对我有用。
try {
String url = "<destination-path>";
String fileName = ""; //file to be uploaded
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
FileBody fileContent = new FiSystem.out.println("hello");
StringBody comment = new StringBody("Filename: " + fileName);
MultipartEntity reqEntity = new MultipartEntity();
reqEntity.addPart("file", fileContent);
httppost.setEntity(reqEntity);
HttpResponse response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();
}
答案 2 :(得分:0)
确定最后一切正常:)我使用了那段代码:
try {
showLog("uploading file: " + file);
File image = new File(pictureFileDir + "/" + file);
FileInputStream fileInputStream = new FileInputStream(image);
URL url = new URL(urlServer);
connection = (HttpURLConnection) url.openConnection();
// Allow Inputs & Outputs.
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
// Set HTTP method to POST.
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=\"" + pictureFileDir + "/" + file + "\"" + lineEnd);
outputStream.writeBytes(lineEnd);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// Read file
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
outputStream.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
outputStream.writeBytes(lineEnd);
outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
// Responses from the server (code and message)
//serverResponseCode = connection.getResponseCode();
serverResponseMessage = connection.getResponseMessage();
showLog("server response: " + serverResponseMessage);
image.delete();
fileInputStream.close();
outputStream.flush();
outputStream.close();
} catch (Exception ex) {
ex.printStackTrace();
}
和PHP脚本:
$target_path = "uploads/";
$target_path = $target_path . basename( $_FILES['uploadedfile']['name']);
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
echo "The file ". basename( $_FILES['uploadedfile']['name'])." has been uploaded";
}
else {
echo "There was an error uploading the file, please try again!";
}
谢谢大家:)