如何将应用程序上传至Web服务器? app怎么传web服务器

随着移动互联网的发展,手机应用已经成为了人们日常生活中不可或缺的一部分 。而对于开发者来说,除了在本地存储数据,也需要将数据传送到Web服务器中 。那么,如何将app上传至Web服务器呢?本文将会为大家详细介绍如何操作 。
1.创建Web服务器
首先 , 需要在Web服务器上建立一个能够接受HTTP POST请求的文件上传文件夹 。并且在此文件夹下的.htaccess文件中添加以下代码 。
php_flag file_uploads on
php_value upload_max_filesize 20M
php_value max_input_time 300
php_value max_execution_time 300
2.编写代码
要将app传送到Web服务器,需要在应用中添加一些必需的代码 。比如 , 需要在应用中添加一个Button控件和一个FileChooser控件,以便于找到需要传送的app文件 。同时,在Button控件设置监听器 , 用于监听点击事件,并且进行上传操作 。以下是具体代码实现 。
button_upload.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("*/*");
intent.addCategory(Intent.CATEGORY_OPENABLE);
startActivityForResult(intent, ACTIVITY_CHOOSE_FILE);
}
});
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == ACTIVITY_CHOOSE_FILE) {
Uri uri = data.getData();
String path = uri.getPath();
String fileNmae = path.substring(path.lastIndexOf("/") + 1);
uploadFile(uri, fileNmae);
}
}
}
private void uploadFile(Uri uri, String fileName) {
try {
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(SERVER_URL);
File file = new File(uri.getPath());
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
builder.addBinaryBody("file",new InputStreamBody(new FileInputStream(file), fileName));
HttpEntity entity = builder.build();
post.setEntity(entity);
HttpResponse response = client.execute(post);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
System.out.println("上传成功!");
} else {
System.out.println("上传失败!");
}
} catch (Exception e) {
e.printStackTrace();
}
}
3.上传app至Web服务器
最后一步,就是将app文件传送到Web服务器上 。这里需要注意的是,需要使用HttpClient类实现上传功能,并且,需要添加其它必需的jar包 。在代码中 , 可以通过以下方式实现上传 。
HttpClient client = new DefaultHttpClient(); // 创建HttpClient对象
HttpPost post = new HttpPost(SERVER_URL); // 构造POST请求
【如何将应用程序上传至Web服务器? app怎么传web服务器】File file = new File(filePath); // 创建文件对象
MultipartEntityBuilder builder = MultipartEntityBuilder.create(); // 创建MultipartEntityBuilder对象
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
builder.addBinaryBody("file", new InputStreamBody(new FileInputStream(file), fileName)); // 添加文件和文件名
HttpPost httpPost = new HttpPost(urlString);
httpPost.setEntity(builder.build());
以上就是如何将app传送至Web服务器的详细操作步骤 。需要注意的是,上传前需要在服务器端开启文件上传功能 , 并且,在app中,需要添加相应的控件和必需的代码 , 才能够实现上传功能 。希望本文的介绍能够帮助到大家 。

    推荐阅读