java:使用POST将文件上传到HTTP服务器,服务器代码问题?

Azh*_*har 1 java post http file-transfer

我是java的新手,我必须将文件从Android应用程序传输到服务器.我从链接中获得了帮助

使用POST将文件上载到HTTP服务器.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!";
}
?>
Run Code Online (Sandbox Code Playgroud)

它的PHP代码和完美的工作,但我必须用Java实现服务器端代码而不是PHP.

我用Google搜索并从链接中找到代码,在此输入链接说明

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();
Run Code Online (Sandbox Code Playgroud)

我是java的新手,所以不知道如何编写这段代码.我安装了NetBeans netbeans-7.1.1-ml-javaee.

有人可以告诉我,如果这段代码是正确的,如何把它放在文件或哪种类型的文件中.我已创建项目但不知道如何将此代码放入文件中.

编辑:

Andriod代码工作正常...我想开发服务器代码来获取和保存文件

Aka*_*ngh 5

我希望这段代码可以帮到你

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());     
    }
Run Code Online (Sandbox Code Playgroud)

其中SmallyTaxiTabbar.unique_ID,密码是参数值

*我希望这段代码可以帮到你!*