我是 java 的新手,我必须将文件从 Android 应用程序传输到服务器。我从链接中获得了帮助
Uploading files to HTTP server using POST. Android SDK
<?php
$target_path = "./";
$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!";
}
?>
它的 PHP 代码运行得非常好,但我必须用 Java 而不是 PHP 来实现服务器端代码。
我用谷歌搜索并从链接 enter link description here 中找到代码
InputStream in = request.getInputStream();
BufferedReader r = new BufferedReader(new InputStreamReader(in));
StringBuffer buf = new StringBuffer();
String line;
while ((line = r.readLine())!=null) {
buf.append(line);
}
String s = buf.toString();
我是 java 的新手,所以不知道如何编写这段代码。我安装了 NetBeans netbeans-7.1.1-ml-javaee。
有人能告诉我这段代码是否正确以及如何将其放入文件或哪种类型的文件中。我已经创建了项目,但不知道如何将此代码放入文件中。
编辑:
Andriod 代码工作正常......我想开发服务器代码来获取和保存文件
最佳答案
希望这段代码能帮到你
try {
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(Image_url);
MultipartEntity mpEntity = new MultipartEntity();
File file = new File(selectedImagePath);
ContentBody cbFile = new FileBody(file, "image/jpeg");
mpEntity.addPart("photo", cbFile);
mpEntity.addPart("user_id", new StringBody(SmallyTaxiTabbar.unique_ID));
mpEntity.addPart("password", new StringBody(SmallyTaxiTabbar.password));
post.setEntity(mpEntity);
HttpResponse response1 = client.execute(post);
HttpEntity resEntity = response1.getEntity();
String Response=EntityUtils.toString(resEntity);
Log.d("PICTUREServer Response", Response);
JSONArray jsonarray = new JSONArray("["+Response+"]");
JSONObject jsonobject = jsonarray.getJSONObject(0);
alert=(jsonobject.getString("alert"));
client.getConnectionManager().shutdown();
}
catch (Exception e) {
Log.e("TAGPost", e.toString());
}
其中SmallyTaxiTabbar.unique_ID,password为参数值
*我希望这段代码能帮到你! *
关于java : upload files to HTTP server using POST, 服务器代码问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10136023/