- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我正在使用 GDK 为 google glass 开发一个应用程序,我正在尝试使用 MultiPartEntity 上传我捕获的图像,但由于某种原因我无法让它工作我无法弄清楚,因为它没有返回任何错误。到目前为止,这就是我所在的位置。
Java
String picturePath = data.getStringExtra(Intents.EXTRA_PICTURE_FILE_PATH);
final File pictureFile = new File(picturePath);
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("SERVER PATH");
try {
@SuppressWarnings("deprecation")
MultipartEntity entity = new MultipartEntity();
entity.addPart("type", new StringBody("photo"));
entity.addPart("data", new FileBody(pictureFile));
httppost.setEntity(entity);
HttpResponse response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
PHP 代码:
$response = array();
$file_upload_url = 'UPLOAD PATH';
if (isset($_FILES['image']['name'])) {
$target_path = $target_path . basename($_FILES['image']['name']);
$email = isset($_POST['email']) ? $_POST['email'] : '';
$website = isset($_POST['website']) ? $_POST['website'] : '';
$response['file_name'] = basename($_FILES['image']['name']);
$response['email'] = $email;
$response['website'] = $website;
try {
// Throws exception incase file is not being moved
if (!move_uploaded_file($_FILES['image']['tmp_name'], $target_path)) {
// make error flag true
$response['error'] = true;
$response['message'] = 'Could not move the file!';
}
// File successfully uploaded
$response['message'] = 'File uploaded successfully!';
$response['error'] = false;
$response['file_path'] = $file_upload_url . basename($_FILES['image']['name']);
} catch (Exception $e) {
// Exception occurred. Make error flag true
$response['error'] = true;
$response['message'] = $e->getMessage();
}
} else {
// File parameter is missing
$response['error'] = true;
$response['message'] = 'Not received any file!';
}
echo json_encode($response);
?>
任何帮助将不胜感激。
最佳答案
这是我的代码。它对我有用。您可以使用此代码发送带有进度条的参数和文件。
public class SendFile extends AsyncTask<String, Integer, Integer> {
private Context conT;
private ProgressDialog dialog;
private String SendUrl = "";
private String SendFile = "";
private String Parameters = "";
private String result;
public File file;
SendFile(Context activity, String url, String filePath, String values) {
conT = activity;
dialog = new ProgressDialog(conT);
SendUrl = url;
SendFile = filePath;
Parameters = Values;
}
@Override
protected void onPreExecute() {
file = new File(SendFile);
dialog.setMessage("Please Wait..");
dialog.setCancelable(false);
dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
dialog.setMax((int) file.length());
dialog.show();
}
@Override
protected Integer doInBackground(String... params) {
HttpURLConnection connection = null;
DataOutputStream outputStream = null;
InputStream inputStream = null;
String twoHyphens = "--";
String boundary = "*****"
+ Long.toString(System.currentTimeMillis()) + "*****";
String lineEnd = "\r\n";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 512;
String[] q = SendFile.split("/");
int idx = q.length - 1;
try {
FileInputStream fileInputStream = new FileInputStream(file);
URL url = new URL(SendUrl);
connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
connection.setRequestMethod("POST");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("User-Agent",
"Android Multipart HTTP Client 1.0");
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=dosya; filename=\""
+ q[idx] + "\"" + lineEnd);
outputStream.writeBytes("Content-Type: image/jpg" + lineEnd);
outputStream.writeBytes("Content-Transfer-Encoding: binary"
+ lineEnd);
outputStream.writeBytes(lineEnd);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
int boyut = 0;
while (bytesRead > 0) {
boyut += bytesRead;
outputStream.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
dialog.setProgress(boyut);
}
outputStream.writeBytes(lineEnd);
String[] posts = Bilgiler.split("&");
int max = posts.length;
for (int i = 0; i < max; i++) {
outputStream.writeBytes(twoHyphens + boundary + lineEnd);
String[] kv = posts[i].split("=");
outputStream
.writeBytes("Content-Disposition: form-data; name=\""
+ kv[0] + "\"" + lineEnd);
outputStream.writeBytes("Content-Type: text/plain"
+ lineEnd);
outputStream.writeBytes(lineEnd);
outputStream.writeBytes(kv[1]);
outputStream.writeBytes(lineEnd);
}
outputStream.writeBytes(twoHyphens + boundary + twoHyphens
+ lineEnd);
inputStream = connection.getInputStream();
result = this.convertStreamToString(inputStream);
Log.v("TAG","result:"+result);
fileInputStream.close();
inputStream.close();
outputStream.flush();
outputStream.close();
} catch (Exception e) {
}
return null;
}
@Override
protected void onProgressUpdate(Integer... progress) {
dialog.setProgress(progress[0]);
}
@Override
protected void onPostExecute(Integer result1) {
dialog.dismiss();
};
private String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(
new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
如果你发送到 PHP,你可以使用这个
<?php
$file_path = "test/";
$username= $_POST["username"];
$password= $_POST["password"];
$file_path = $file_path . basename( $_FILES['uploaded_file']['name']);
if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $file_path)) {
echo "success";
} else{
echo "fail";
}
?>
编辑 - 2:
你可以这样调用这个 AsyncTask :
String FormData = "username=" + Session.getUsername()
+ "&password=" + Session.getPassword() ;
SendFile SendIt= new SendFile(this, upLoadServerUri, filePath,FormData);
SendIt.execute();
关于java - Android使用GDK使用MultipartEntity上传图片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27684440/
可能这是一个重复的问题,但我已经尝试过该网站的所有答案,但都不起作用! 我正在使用 MultipartEntity 进行图像上传。它在模拟器中工作得很好,但是当我 checkin 设备时它不工作。 在
所以我创建了一个 Workout 类,我想使用 HttpPost 将它发送到服务器。有什么方法可以将该类添加到 MultipartEntity 中,或者我应该如何发布它? 最佳答案 首先,您的类必须实
我想使用 MultipartEntity 上传图片。我尝试了以下代码。 我没有收到任何错误,但图片未上传。我有足够的上传权限 PHP 'success', 'm
在我开始之前,我看到了很多关于这个的问题,但对我来说没有任何用处也许有人可以向我解释或向我展示如何将位图压缩为 MultiPart 实体,然后使用 Retrofit 将其正确发送到服务器 最佳答案 对
不确定为什么会这样,但这行代码使我的应用程序在调试或运行模式下崩溃: MultipartEntity multipartEntity = new MultipartEntity(HttpMultipa
我最近将我的项目从 Eclipse 迁移到 Android Studio(我还没有完全控制这个 IDE)。在这个项目中,我有一个文件 uploader AsyncTask,它通过 http 发送多部分
文档说 org.apache.http.entity.mime.MultipartEntity类已弃用。有人可以给我推荐一个替代方案吗? 我在我的代码中这样使用它: entity.addPart("p
我想使用 MultipartEntity 上传单张图片。我尝试了以下代码。 但是图片没有上传。我没有收到任何错误。我已经为此添加了足够的库 try { HttpClient
这是我目前所拥有的: MultipartEntity reqEntity = new MultipartEntity(); String strXMLFilename = "/sdcard/image
我想使用 MultipartEntity 将图像和 JsonObject 发送到 PHP 服务器。这是我的代码: HttpClient httpClient = new DefaultHttpClie
我正在使用 MultiPartEntity 在我的 Android 应用程序中发布 XML + 图片,一切都很好,除了我要发布到的服务器要求我设置 Content- HTTP post 的类型到app
我在 MultipartEntity 中传递 3 张图像。这很好用,但我不知道如何将 String 值传递给 MultipartEntity。以下是我的代码: public void executeM
我一直在尝试将图像和数据上传到 Django 服务器。我包含了 apache-mime4j.0.6.jar 和 httpmime4.0.1.jar 库(Project->build path->Add
我想将文件的内容作为 org.apache.http.entity.mime.MultipartEntity 发送。问题是,我实际上没有文件,只有 String 形式的内容。以下测试完美运行,其中 f
如何执行此代码以便它在后台线程中发送? // TODO: Send image in background HttpClient httpclient = new Defaul
我需要将其解析为 JsonArray 而不是对象但它似乎无法正常工作。 my output is ["{"TransactionVolume":"34","TransactionitemID":"2"
我想在我的 AndroidHttpClient 中实现一个 ProgressDialog。我在这里找到了一个简单的实现 CountingMultipartEntity . 另外我添加了内容长度支持。我
我尝试在 Android 中使用 MultiPartEntity 和 HttpClient 发送图像,但不断收到异常:java.lang.UnsupportedOperationException:
我正在尝试使用 HttpClient 和 MultipartEntity 将图像从 Adroid 应用程序上传到 php 网络服务器。 这是我的代码 fragment : protected Void
我现在有一个 Tomcat 实例,它接受上传并对数据进行一些处理工作。 我想用符合类似 API 的新 servlet 替换它。首先,我希望这个新 servlet 将所有请求代理到旧的 servlet。
我是一名优秀的程序员,十分优秀!