我是android应用程序开发的新手,试图开发一个web视图应用程序,但似乎无法让文件上传工作。。。请帮忙
这是我的网页视图代码
package com.example.project;
公共类WebActive扩展了活动{
private WebView wv;
private String LASTURL = "";
Menu myMenu = null;
private ProgressDialog dialog;
private ValueCallback<Uri> mUploadMessage;
private final static int FILECHOOSER_RESULTCODE=1;
@Override
protected void onActivityResult(int requestCode, int resultCode,
Intent intent) {
if(requestCode==FILECHOOSER_RESULTCODE)
{
if (null == mUploadMessage) return;
Uri result = intent == null || resultCode != RESULT_OK ? null
: intent.getData();
mUploadMessage.onReceiveValue(result);
mUploadMessage = null;
}
}
/**
* Called when the activity is first created.
*/
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.getWindow().requestFeature(Window.FEATURE_PROGRESS);
if (!InternetConnection.checkNetworkConnection(this)) {
showAlert(this, "No Data Connection", "This Application requires an internet connection");
} else {
setContentView(R.layout.web_view);
wv = (WebView) findViewById(R.id.web_view);
WebSettings webSettings = wv.getSettings();
webSettings.setSavePassword(true);
webSettings.setSaveFormData(true);
webSettings.setJavaScriptEnabled(true);
webSettings.setUseWideViewPort(true);
webSettings.setLoadWithOverviewMode(true);
webSettings.setSupportZoom(false);
final Activity activity = this;
// start ProgressDialog with "Page loading..."
dialog = new ProgressDialog(activity);
dialog.setMessage("Loading...");
dialog.setIndeterminate(true);
dialog.setCancelable(true);
dialog.show();
wv.setWebChromeClient(new WebChromeClient() {
public void onProgressChanged(WebView view, int progress) {
// set address bar and progress
// activity.setTitle( " " + LASTURL );
// activity.setProgress( progress * 100 );
if (progress == 100) {
// stop ProgressDialog after loading
dialog.dismiss();
// activity.setTitle( " " + LASTURL );
}
}
});
wv.setWebViewClient(new WebViewClient() {
public void onReceivedError(WebView view, int errorCode,
String description, String failingUrl) {
Toast.makeText(getApplicationContext(),
"Error: " + description + " " + failingUrl,
Toast.LENGTH_LONG).show();
}
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url.indexOf("mycitygist") <= 0) {
// the link is not for a page on my site, so launch
// another Activity that handles URLs
Intent intent = new Intent(Intent.ACTION_VIEW, Uri
.parse(url));
startActivity(intent);
return true;
}
return false;
}
/*****************************************************************/
/* Here the load of the page will start so we must launch the */
/* ProgressDialog */
/*****************************************************************/
public void onPageStarted(WebView view, String url,
Bitmap favicon) {
// this is what we should do
dialog.setMessage("Loading...");
dialog.setIndeterminate(true);
dialog.setCancelable(true);
dialog.show();
//
LASTURL = url;
view.getSettings().setLoadsImagesAutomatically(true);
view.getSettings().setBuiltInZoomControls(true);
}
/*****************************************************************/
/* Here the load of the page will stop so we must dismiss the */
/* ProgressDialog */
/*****************************************************************/
public void onPageFinished(WebView view, String url) {
// this is what we should do
dialog.dismiss();
}
});
wv.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
wv.setScrollbarFadingEnabled(false);
wv.loadUrl("http://app.mycitygist.com/overview/");
}
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK) && wv.canGoBack()) {
wv.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
this.myMenu = menu;
MenuItem item = menu.add(0, 1, 0, "Home");
item.setIcon(R.drawable.home);
MenuItem item2 = menu.add(0, 2, 0, "Back");
item2.setIcon(R.drawable.arrowleft);
MenuItem item3 = menu.add(0, 3, 0, "Reload");
item3.setIcon(R.drawable.s);
MenuItem item4 = menu.add(0, 4, 0, "Share");
item4.setIcon(R.drawable.share);
MenuItem item5 = menu.add(0, 5, 0, "Rate");
item5.setIcon(R.drawable.vote);
MenuItem item6 = menu.add(0, 6, 0, "Exit");
item6.setIcon(R.drawable.close);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case 1:
wv.loadUrl("http://http://app.mycitygist.com/overview/");
break;
case 2:
if (wv.canGoBack()) {
wv.goBack();
}
break;
case 3:
wv.loadUrl(LASTURL);
break;
case 4:
Intent sharingIntent = new Intent(Intent.ACTION_SEND);
sharingIntent.setType("plain/text");
sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, "Check out this app I found.");
startActivity(Intent.createChooser(sharingIntent,"Share using"));
break;
case 5:
Intent marketIntent2 = new Intent(Intent.ACTION_VIEW, Uri.parse(
"http://market.android.com/details?id=" + getPackageName()));
startActivity(marketIntent2);
break;
case 6:
finish();
break;
}
return true;
}
/**
* Display a simple alert dialog with the given text and title.
*
* @param context
* Android context in which the dialog should be displayed
* @param title
* Alert dialog title
* @param text
* Alert dialog message
*/
public void showAlert(Context context, String title, String text) {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
// set title
alertDialogBuilder.setTitle( title);
// set dialog message
alertDialogBuilder
.setMessage( text )
.setCancelable(false)
.setPositiveButton("OK",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
// if this button is clicked, close
// current activity
finish();
}
})
.create().show();
}
}
所以我在wv下添加了这个代码。setWebChromeClient//未记录的魔术方法覆盖//br>//如果您尝试在此处放置@override,Eclipse将对您发誓//Android 3.0 public void openFileChooser(ValueCallback uploadMsg){
mUploadMessage = uploadMsg;
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("image/*");
WebActivity.this.startActivityForResult(Intent.createChooser(i,"File Chooser"), FILECHOOSER_RESULTCODE);
}
// For Android 3.0+
public void openFileChooser( ValueCallback uploadMsg, String acceptType ) {
mUploadMessage = uploadMsg;
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("*/*");
WebActivity.this.startActivityForResult(
Intent.createChooser(i, "File Browser"),
FILECHOOSER_RESULTCODE);
}
//For Android 4.1
public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture){
mUploadMessage = uploadMsg;
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("image/*");
WebActivity.this.startActivityForResult( Intent.createChooser( i, "File Chooser" ), WebActivity.FILECHOOSER_RESULTCODE );
}
});
setContentView(wv);
}
}
似乎无法编译包含这行代码的应用程序,但没有它,d应用程序编译良好,运行良好,但没有文件上传功能
请参阅此代码,我正在使用文件选择按钮选择文件,稍后将在我的jsp中使用上载
AndroidManifest.xml:
-------------------
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.MANAGE_DOCUMENTS"
tools:ignore="ProtectedPermissions" />
MainActivity.java:
--------------------
package com.example.satis.image_text;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Parcelable;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class MainActivity extends AppCompatActivity {
private static final int INPUT_FILE_REQUEST_CODE = 1;
private static final int FILECHOOSER_RESULTCODE = 1;
private static final String TAG = MainActivity.class.getSimpleName();
private WebView webView;
private WebSettings webSettings;
private ValueCallback<Uri> mUploadMessage;
private Uri mCapturedImageURI = null;
private ValueCallback<Uri[]> mFilePathCallback;
private String mCameraPhotoPath;
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
if (requestCode != INPUT_FILE_REQUEST_CODE || mFilePathCallback == null) {
super.onActivityResult(requestCode, resultCode, data);
return;
}
Uri[] results = null;
// Check that the response is a good one
if (resultCode == Activity.RESULT_OK) {
if (data == null) {
// If there is not data, then we may have taken a photo
if (mCameraPhotoPath != null) {
results = new Uri[]{Uri.parse(mCameraPhotoPath)};
}
} else {
String dataString = data.getDataString();
if (dataString != null) {
results = new Uri[]{Uri.parse(dataString)};
}
}
}
mFilePathCallback.onReceiveValue(results);
mFilePathCallback = null;
} else if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT) {
if (requestCode != FILECHOOSER_RESULTCODE || mUploadMessage == null) {
super.onActivityResult(requestCode, resultCode, data);
return;
}
if (requestCode == FILECHOOSER_RESULTCODE) {
if (null == this.mUploadMessage) {
return;
}
Uri result = null;
try {
if (resultCode != RESULT_OK) {
result = null;
} else {
// retrieve from the private variable if the intent is null
result = data == null ? mCapturedImageURI : data.getData();
}
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "activity :" + e,
Toast.LENGTH_LONG).show();
}
mUploadMessage.onReceiveValue(result);
mUploadMessage = null;
}
}
return;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webView = (WebView) findViewById(R.id.webview);
webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setLoadWithOverviewMode(true);
webSettings.setAllowFileAccess(true);
webView.setWebViewClient(new Client());
webView.setWebChromeClient(new ChromeClient());
if (Build.VERSION.SDK_INT >= 19) {
webView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
}
else if(Build.VERSION.SDK_INT >=11 && Build.VERSION.SDK_INT < 19) {
webView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
}
webView.loadUrl("http://ec2-107-23-105-200.compute-1.amazonaws.com:8080/Action_file.jsp"); //change with your website
}
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES);
File imageFile = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
return imageFile;
}
public class ChromeClient extends WebChromeClient {
// For Android 5.0
public boolean onShowFileChooser(WebView view, ValueCallback<Uri[]> filePath, WebChromeClient.FileChooserParams fileChooserParams) {
// Double check that we don't have any existing callbacks
if (mFilePathCallback != null) {
mFilePathCallback.onReceiveValue(null);
}
mFilePathCallback = filePath;
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
takePictureIntent.putExtra("PhotoPath", mCameraPhotoPath);
} catch (IOException ex) {
// Error occurred while creating the File
Log.e(TAG, "Unable to create Image File", ex);
}
// Continue only if the File was successfully created
if (photoFile != null) {
mCameraPhotoPath = "file:" + photoFile.getAbsolutePath();
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.fromFile(photoFile));
} else {
takePictureIntent = null;
}
}
Intent contentSelectionIntent = new Intent(Intent.ACTION_GET_CONTENT);
contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE);
contentSelectionIntent.setType("image/*");
Intent[] intentArray;
if (takePictureIntent != null) {
intentArray = new Intent[]{takePictureIntent};
} else {
intentArray = new Intent[0];
}
Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER);
chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent);
chooserIntent.putExtra(Intent.EXTRA_TITLE, "Image Chooser");
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray);
startActivityForResult(chooserIntent, INPUT_FILE_REQUEST_CODE);
return true;
}
// openFileChooser for Android 3.0+
public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
mUploadMessage = uploadMsg;
// Create AndroidExampleFolder at sdcard
// Create AndroidExampleFolder at sdcard
File imageStorageDir = new File(
Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES)
, "AndroidExampleFolder");
if (!imageStorageDir.exists()) {
// Create AndroidExampleFolder at sdcard
imageStorageDir.mkdirs();
}
// Create camera captured image file path and name
File file = new File(
imageStorageDir + File.separator + "IMG_"
+ String.valueOf(System.currentTimeMillis())
+ ".jpg");
mCapturedImageURI = Uri.fromFile(file);
// Camera capture image intent
final Intent captureIntent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
captureIntent.putExtra(MediaStore.EXTRA_OUTPUT, mCapturedImageURI);
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("image/*");
// Create file chooser intent
Intent chooserIntent = Intent.createChooser(i, "Image Chooser");
// Set camera intent to file chooser
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS
, new Parcelable[] { captureIntent });
// On select image call onActivityResult method of activity
startActivityForResult(chooserIntent, FILECHOOSER_RESULTCODE);
}
// openFileChooser for Android < 3.0
public void openFileChooser(ValueCallback<Uri> uploadMsg) {
openFileChooser(uploadMsg, "");
}
//openFileChooser for other Android versions
public void openFileChooser(ValueCallback<Uri> uploadMsg,
String acceptType,
String capture) {
openFileChooser(uploadMsg, acceptType);
}
}
public boolean onKeyDown(int keyCode, KeyEvent event) {
// Check if the key event was the Back button and if there's history
if ((keyCode == KeyEvent.KEYCODE_BACK) && webView.canGoBack()) {
webView.goBack();
return true;
}
// If it wasn't the Back key or there's no web page history, bubble up to the default
// system behavior (probably exit the activity)
return super.onKeyDown(keyCode, event);
}
public class Client extends WebViewClient {
ProgressDialog progressDialog;
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// If url contains mailto link then open Mail Intent
if (url.contains("mailto:")) {
// Could be cleverer and use a regex
//Open links in new browser
view.getContext().startActivity(
new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
// Here we can open new activity
return true;
}else {
// Stay within this webview and load url
view.loadUrl(url);
return true;
}
}
//Show loader on url load
public void onPageStarted(WebView view, String url, Bitmap favicon) {
// Then show progress Dialog
// in standard case YourActivity.this
if (progressDialog == null) {
progressDialog = new ProgressDialog(MainActivity.this);
progressDialog.setMessage("Loading...");
progressDialog.show();
}
}
// Called when all page resources loaded
public void onPageFinished(WebView view, String url) {
try {
// Close progressDialog
if (progressDialog.isShowing()) {
progressDialog.dismiss();
progressDialog = null;
}
} catch (Exception exception) {
exception.printStackTrace();
}
}
}
}
enter code here
我想将文件从一台服务器上传到另一台FTP服务器,以下是我的上传文件代码,但它抛出错误为: 远程服务器返回错误:(550)文件不可用(例如,找不到文件,无法访问)。 这是我的代码: 你能告诉我哪里出了问题吗?
问题内容: 我正在使用Flash录制音频并将其上传到节点服务器。Flash客户端是jrecorder的变体。当用户完成录制后,将使用POST请求(而不是表单,因为Flash无法创建文件)来上传音频,并将音频ByteArray作为POST请求的数据(请参见此处的更多信息)。 我可以使用下面的代码在Node- land上正确接收文件,但是发出的音频被破坏了,您听不到任何声音。话虽如此,该文件的内容可以
在Yii里上传文件通常使用 yii\web\UploadedFile 类, 它把每个上传的文件封装成 UploadedFile 对象。 结合 yii\widgets\ActiveForm 和 models,你可以轻松实现安全的上传文件机制。 创建模型 和普通的文本输入框类似,当要上传一个文件时,你需要创建一个模型类并且用其中的某个属性来接收上传的文件实例。 你还需要声明一条验证规则以验证上传的文件
大多数的 Web 应用都不可避免的,会涉及到文件上传。文件上传,不过是一种适配 HTTP 输入流的方式。 为此,Nutz.Mvc 内置了一个专门处理文件上传的适配器 org.nutz.mvc.upload.UploadAdaptor 这个适配器专门解析形式为 <form target="hideWin" enctype="multipart/form-data" method="post">
哦,上传文件可是个经典的好问题了。文件上传的基本概念实际上非常简单, 他基本是这样工作的: 一个 <form> 标签被标记有 enctype=multipart/form-data ,并且 在里面包含一个 <input type=file> 标签。 服务端应用通过请求对象上的 files 字典访问文件。 使用文件的 save() 方法将文件永久地 保存在文件系统上的某处。 一点点介绍 让我们建立一
Django提供了一些类实现管理数据分页,这些类位于django/core/paginator.py中 Paginator对象 Paginator(列表,int):返回分页对象,参数为列表数据,每面数据的条数 属性 count:对象总数 num_pages:页面总数 page_range:页码列表,从1开始,例如[1, 2, 3, 4] 方法 page(num):下标以1开始,如果提供的页码不存在