我正在生成一个文件夹,我正在创建一个文本文件并使用此函数将它们存储在缓存目录中:
public void GenerateFile(String sFileName, String sBody){
try
{
String foldername="TestFolder";
File root = new File(context.getCacheDir() + "/"+foldername);
if (!root.exists()) {
root.mkdirs();
}
File gpxfile = new File(root, sFileName);
FileWriter writer = new FileWriter(gpxfile);
writer.append(sBody);
writer.flush();
writer.close();
Toast.makeText(context, "Saved", Toast.LENGTH_SHORT).show();
}
catch(Exception e)
{
Log.d("Exception is",e.toString());
}
}
然后我试图在服务器上发布这个文件,这是我的活动:
GenerateFile("ConfigFile.txt","test\ndfssdfdsf\ndfsdsdfsfds\nsdfdfs");
uploadFilePath=this.getCacheDir() + "/TestFolder/ConfigFile.txt";
upLoadServerUri = "http://www.*****.com/test/uploadtoserver.php";
uploadButton.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
dialog = ProgressDialog.show(PostFile.this, "", "Uploading file...", true);
new Thread(new Runnable()
{
public void run()
{
runOnUiThread(new Runnable()
{
public void run()
{
messageText.setText("uploading started.....");
}
});
uploadFile(uploadFilePath);
}
}).start();
}
});
}
public int uploadFile(String sourceFileUri)
{
String fileName = sourceFileUri;
HttpURLConnection conn = null;
DataOutputStream dos = null;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
File sourceFile = new File(sourceFileUri);
if (!sourceFile.isFile())
{
dialog.dismiss();
Log.e("uploadFile", "Source File not exist :"
+ uploadFilePath);
runOnUiThread(new Runnable() {
public void run() {
messageText.setText("Source File not exist :" + uploadFilePath);
}
});
return 0;
}
else
{
try
{
// open a URL connection to the Servlet
FileInputStream fileInputStream = new FileInputStream(sourceFile);
URL url = new URL(upLoadServerUri);
// Open a HTTP connection to the URL
conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true); // Allow Inputs
conn.setDoOutput(true); // Allow Outputs
conn.setUseCaches(false); // Don't use a Cached Copy
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("ENCTYPE", "multipart/form-data");
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
conn.setRequestProperty("myFile",fileName);
Log.d("File Name is", fileName);
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\""
+ fileName + "\"" + lineEnd);
dos.writeBytes(lineEnd);
// create a buffer of maximum size
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// read file and write it into form...
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0)
{
dos.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
// send multipart form data necesssary after file data...
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
// Responses from the server (code and message)
serverResponseCode = conn.getResponseCode();
String serverResponseMessage = conn.getResponseMessage();
Log.i("uploadFile", "HTTP Response is : "
+ serverResponseMessage + ": " + serverResponseCode);
if(serverResponseCode == 200)
{
InputStream in = new BufferedInputStream(conn.getInputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
Log.d("Result is",String.valueOf(result));
}
runOnUiThread(new Runnable()
{
public void run()
{
String msg = "File Upload Completed.\n\n See uploaded file here : \n\n"+" serverpath"
+uploadFileName;
messageText.setText(msg);
Toast.makeText(PostFile.this, "File Upload Complete.",
Toast.LENGTH_SHORT).show();
}
});
}
//close the streams //
fileInputStream.close();
dos.flush();
dos.close();
}
catch (MalformedURLException ex)
{
dialog.dismiss();
ex.printStackTrace();
runOnUiThread(new Runnable()
{
public void run()
{
messageText.setText("MalformedURLException Exception : check script url.");
Toast.makeText(PostFile.this, "MalformedURLException", Toast.LENGTH_SHORT).show();
}
});
Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
}
catch (Exception e)
{
dialog.dismiss();
e.printStackTrace();
runOnUiThread(new Runnable()
{
public void run()
{
messageText.setText("Got Exception : see logcat ");
Toast.makeText(PostFile.this, "Got Exception : see logcat ",
Toast.LENGTH_SHORT).show();
}
});
Log.e("Upload Exception", "Exception : "
+ e.getMessage(), e);
}
dialog.dismiss();
return serverResponseCode;
这是php代码:
<?php
if (!empty($_FILES["myFile"])) {
$myFile = $_FILES["myFile"];
if ($myFile["error"] !== UPLOAD_ERR_OK) {
echo "error";
}
else{
$filename = $_FILES['myFile']['name'];
$ext = pathinfo($filename, PATHINFO_EXTENSION);
echo "success -- extension: ." . $ext;
}
}
else{
echo "no file found";
}
?>
文件没有上传,php页面没有找到找到的文件,有什么帮助吗?
答案 0 :(得分:0)
您是否已验证用户apache(或运行的用户php)是否有权写入$ file_path中指定的目录?
将以下代码放在与PHP脚本相同的目录中,然后在Web浏览器中访问它。
<?php
$file_path = 'uploads/';
$success = file_put_contents($file_path . "afile", "This is a test");
if($success === false) {
echo "Couldn't write file";
} else {
echo "Wrote $success bytes";
}
?>
这会给出成功消息还是错误消息?
如果它给出错误消息,请尝试更改uploads目录的所有权。
答案 1 :(得分:0)
试试这个。 我已经测试了这段代码,它可以正常用于图片上传
// Get image string posted from Android App
$base = $_POST["image"];
// Get file name posted from Android App
$filename = $_POST["filename"];
// Decode Image
$binary=base64_decode($base);
header('Content-Type: bitmap; charset=utf-8');
// Images will be saved under 'www/imgupload/uplodedimages' folder
$file = fopen($filename, 'wb');
// Create File
fwrite($file, $binary);
fclose($file);
echo 'Image upload complete, Please check your php file directory';