实现JAVA上传数据至PHP服务器存储(SAE)

来源:互联网 发布:单片机调试 编辑:程序博客网 时间:2024/06/05 18:50

Java客户端实现数据上传至PHP服务器(搭载在SAE)


PHP上传功能DEMO:

<html><head><title>上传文件</title></head><body><form enctype="multipart/form-data"  method="post"><input name="myfile" type="file"/><input type="submit" name="up" value="上传"/></form></body></html><?phpif(isset($_POST[up])){    $s2 =new SaeStorage();//实例化    $name =$_FILES['myfile']['name'];//上传到服务器的文件名称    if($s2->upload('20141001challenge',$name,$_FILES['myfile']['tmp_name'])){//服务器Domain Name,传到服务器的文件名,本地文件名         echo "OK";         echo $s2->getUrl("20141001challenge",$name);//输出上传文件在storage的访问路径    }else{         echo "FAIL";    }}?>



也是简陋的~~(请忽略download按钮。。)

PHP部分的还是比较简单的,这已经可以点击选择需要的图片上传了。

但在JAVA上如何触发这个上传的按钮的?

我们可以写一个方法来调用这个操作过程,然后通过Java来访问这个方法。

具体如下

PHP方法:

(//将isset函数去掉,否则java程序上传时无法进入存储过程)

function upload(){        $s2 =new SaeStorage();//实例化        $name =$_FILES['myfile']['name'];//上传到服务器的文件名称        if($s2->upload('20141001challenge',$name,$_FILES['myfile']['tmp_name'])){//服务器Domain Name,传到服务器的文件名,本地文件名         echo "OK";           echo $s2->getUrl("20141001challenge",$name);//输出上传文件在storage的访问路径        }else{           echo "FAIL";        }}

方法的调用过程自行学习PHP...


本人是用快速框架搭的PHP后台,所以直接这样用:

        $posturl0 = spUrl("main", "upload"); //将上传功能放在方法内        echo "<form action={$posturl0} enctype='multipart/form-data'  method='post'>                <input name='myfile' type='file'/>                <input type='submit' name='up' value='上传'/>                </form>";


最后就是有JAVA程序来访问这个方法了:

public class Upload {private static String srcPath = "E:\\jd-gui.exe";  //绝对路径噢public static void main(String[] args) {uploadFile("http://xxxx.xxxx.com/index.php?c=main&a=upload");}  /* 上传文件至Server,uploadUrl:接收文件的处理页面 */  private static void uploadFile(String uploadUrl)  {    String end = "\r\n";    String twoHyphens = "--";    String boundary = "******";    try    {      URL url = new URL(uploadUrl);      HttpURLConnection httpURLConnection = (HttpURLConnection) url          .openConnection();      // 设置每次传输的流大小,可以有效防止手机因为内存不足崩溃      // 此方法用于在预先不知道内容长度时启用没有进行内部缓冲的 HTTP 请求正文的流。      httpURLConnection.setChunkedStreamingMode(128 * 1024);// 128K      // 允许输入输出流      httpURLConnection.setDoInput(true);// 允许输入流      httpURLConnection.setDoOutput(true);// 允许输出流      httpURLConnection.setUseCaches(false);// 不允许使用缓存      // 使用POST方法      httpURLConnection.setRequestMethod("POST");      httpURLConnection.setRequestProperty("Connection", "Keep-Alive");      httpURLConnection.setRequestProperty("Charset", "UTF-8");      httpURLConnection.setRequestProperty("Content-Type",          "multipart/form-data;boundary=" + boundary);      DataOutputStream dos = new DataOutputStream(          httpURLConnection.getOutputStream());      dos.writeBytes(twoHyphens + boundary + end);      dos.writeBytes("Content-Disposition: form-data; name=\"myfile\"; filename=\""          + srcPath.substring(srcPath.lastIndexOf("/") + 1)          + "\""          + end);      dos.writeBytes(end);            FileInputStream fis = new FileInputStream(srcPath);      byte[] buffer = new byte[8192]; // 8k      int count = 0;      // 读取文件      while ((count = fis.read(buffer)) != -1)      {        dos.write(buffer, 0, count);      }      fis.close();      dos.writeBytes(end);      dos.writeBytes(twoHyphens + boundary + twoHyphens + end);      dos.flush();      InputStream is = httpURLConnection.getInputStream();      InputStreamReader isr = new InputStreamReader(is, "utf-8");      BufferedReader br = new BufferedReader(isr);      String result = br.readLine();      System.out.println(result);      dos.close();      is.close();    } catch (Exception e)    {      e.printStackTrace();      System.out.println(e.getMessage());    }  }}

到此全部解说完毕。

另外提出一点:也可以通过将数据转码以后上传,在服务器转码还原存储,这也是可以实现的方法。


2015.5.27:

上面是将后台网址作为入口。

然而一般都是将上传路径作为入口的吧,如下:

<span style="font-size:14px;">import java.io.BufferedReader;import java.io.DataOutputStream;import java.io.FileInputStream;import java.io.InputStream;import java.io.InputStreamReader;import java.net.HttpURLConnection;import java.net.URL;import java.util.ArrayList;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;public class Upload {public static void main(String[] args) {final ArrayList<String> array = new ArrayList<String>();array.add("E:\\main.php");array.add("E:\\jd-gui.exe");array.add("E:\\非单片机学习视频\\PHP从入门到精通笔记_韩顺平181页-官网整理.doc");//开一个线程池上传。ExecutorService fixedThreadPool = Executors.newFixedThreadPool(1);for (int i = 0; i < array.size(); i++) {final int temp = i;fixedThreadPool.execute(new Runnable() {public void run() {uploadFile(array.get(temp));System.out.println("get the "+temp);}});}}  /* 上传文件至Server,uploadUrl:接收文件的处理页面 */  private static void uploadFile(String srcPath)  {    String end = "\r\n";    String twoHyphens = "--";    String boundary = "******";    try    {      URL url = new URL("http://x.xxxxxx.sinaapp.com/index.php?c=main&a=upload");      HttpURLConnection httpURLConnection = (HttpURLConnection) url          .openConnection();      // 设置每次传输的流大小,可以有效防止手机因为内存不足崩溃      // 此方法用于在预先不知道内容长度时启用没有进行内部缓冲的 HTTP 请求正文的流。      httpURLConnection.setChunkedStreamingMode(128 * 1024);// 128K      // 允许输入输出流      httpURLConnection.setDoInput(true);      httpURLConnection.setDoOutput(true);      httpURLConnection.setUseCaches(false);      // 使用POST方法      httpURLConnection.setRequestMethod("POST");      httpURLConnection.setRequestProperty("Connection", "Keep-Alive");      httpURLConnection.setRequestProperty("Charset", "UTF-8");      httpURLConnection.setRequestProperty("Content-Type",          "multipart/form-data;boundary=" + boundary);      DataOutputStream dos = new DataOutputStream(          httpURLConnection.getOutputStream());      dos.writeBytes(twoHyphens + boundary + end);      dos.writeBytes("Content-Disposition: form-data; name=\"myfile\"; filename=\""          + srcPath.substring(srcPath.lastIndexOf("/") + 1)          + "\""          + end);      dos.writeBytes(end);      FileInputStream fis = new FileInputStream(srcPath);      byte[] buffer = new byte[8192]; // 8k      int count = 0;      // 读取文件      while ((count = fis.read(buffer)) != -1)      {        dos.write(buffer, 0, count);      }      fis.close();      dos.writeBytes(end);      dos.writeBytes(twoHyphens + boundary + twoHyphens + end);      dos.flush();      InputStream is = httpURLConnection.getInputStream();      InputStreamReader isr = new InputStreamReader(is, "utf-8");      BufferedReader br = new BufferedReader(isr);      String result = br.readLine();      System.out.println(result);      dos.close();      is.close();    } catch (Exception e)    {      e.printStackTrace();      System.out.println(e.getMessage());    }  }}</span><span style="font-size:24px;color: rgb(255, 0, 0);"></span>


0 0
原创粉丝点击