从app上传图片到php,再上传到java后端服务器的方法一条龙服务

前端之家收集整理的这篇文章主要介绍了从app上传图片到php,再上传到java后端服务器的方法一条龙服务前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

  在现在的网络开发中,上传图片类的需求实在是太普通不过了,但是对于怎么样做到上传图片,对于刚开始建立项目的时候,还是有点不知所措的。也许有幸,我们做的项目是之前已经有人写过类似的用例了,那么我们只需要依葫芦画瓢就行了。

  好好了解下图片上传文件上传)的方式,对于认知的提升还是有好处的。而且说不定哪天你就有个这样的需求呢,这里是一条龙上传

  本文就一个从app到PHP层,再到java层的流程,演译下整个上传图片的流程吧。

一、app端获取用户选择的图片,转化为输入流,上传PHP前端接口:

<span style="color: #0000ff">import<span style="color: #000000"> java.io.DataOutputStream;
<span style="color: #0000ff">import<span style="color: #000000"> java.io.File;
<span style="color: #0000ff">import<span style="color: #000000"> java.io.FileInputStream;
<span style="color: #0000ff">import<span style="color: #000000"> java.io.IOException;
<span style="color: #0000ff">import<span style="color: #000000"> java.io.InputStream;
<span style="color: #0000ff">import<span style="color: #000000"> java.net.HttpURLConnection;
<span style="color: #0000ff">import<span style="color: #000000"> java.net.MalformedURLException;
<span style="color: #0000ff">import<span style="color: #000000"> java.net.URL;
<span style="color: #0000ff">import<span style="color: #000000"> java.util.HashMap;
<span style="color: #0000ff">import<span style="color: #000000"> java.util.Map;
<span style="color: #0000ff">import<span style="color: #000000"> java.util.UUID;

<span style="color: #008000">/**<span style="color: #008000">

  • 上传文件到服务器类
    <span style="color: #008000">/
    <span style="color: #0000ff">public <span style="color: #0000ff">class<span style="color: #000000"> UploadUtil {
    <span style="color: #0000ff">private <span style="color: #0000ff">static <span style="color: #0000ff">final String TAG = "uploadFile"<span style="color: #000000">;
    <span style="color: #0000ff">private <span style="color: #0000ff">static <span style="color: #0000ff">final <span style="color: #0000ff">int TIME_OUT = 10
    1000; <span style="color: #008000">//<span style="color: #008000"> 超时时间
    <span style="color: #0000ff">private <span style="color: #0000ff">static <span style="color: #0000ff">final String CHARSET = "utf-8"; <span style="color: #008000">//<span style="color: #008000"> 设置编码
    <span style="color: #008000">/**<span style="color: #008000">
    • Android上传文件到服务端
    • <span style="color: #808080">@param<span style="color: #008000"> file 需要上传文件
    • <span style="color: #808080">@param<span style="color: #008000"> RequestURL 请求的rul
    • <span style="color: #808080">@return<span style="color: #008000"> 返回响应的内容
      <span style="color: #008000">*/
      <span style="color: #0000ff">public <span style="color: #0000ff">static<span style="color: #000000"> String uploadFile(File file,String RequestURL) {
      String result = <span style="color: #0000ff">null<span style="color: #000000">;
      String BOUNDARY = UUID.randomUUID().toString(); <span style="color: #008000">//<span style="color: #008000"> 边界标识 随机生成
      String PREFIX = "--",LINE_END = "\r\n"<span style="color: #000000">;
      String CONTENT_TYPE = "multipart/form-data"; <span style="color: #008000">//<span style="color: #008000"> 内容类型
      <span style="color: #0000ff">try<span style="color: #000000"> {
      URL url = <span style="color: #0000ff">new<span style="color: #000000"> URL(RequestURL);
      HttpURLConnection conn =<span style="color: #000000"> (HttpURLConnection) url.openConnection();
      conn.setReadTimeout(TIME_OUT);
      conn.setConnectTimeout(TIME_OUT);
      conn.setDoInput(<span style="color: #0000ff">true); <span style="color: #008000">//<span style="color: #008000"> 允许输入流
      conn.setDoOutput(<span style="color: #0000ff">true); <span style="color: #008000">//<span style="color: #008000"> 允许输出
      conn.setUseCaches(<span style="color: #0000ff">false); <span style="color: #008000">//<span style="color: #008000"> 不允许使用缓存
      conn.setRequestMethod("POST"); <span style="color: #008000">//<span style="color: #008000"> 请求方式
      conn.setRequestProperty("Charset",CHARSET); <span style="color: #008000">//<span style="color: #008000"> 设置编码
      conn.setRequestProperty("connection","keep-alive"<span style="color: #000000">);
      conn.setRequestProperty("Content-Type",CONTENT_TYPE + ";boundary=" +<span style="color: #000000"> BOUNDARY);
      <span style="color: #0000ff">if (file != <span style="color: #0000ff">null<span style="color: #000000">) {
      DataOutputStream dos = <span style="color: #0000ff">new<span style="color: #000000"> DataOutputStream(conn.getOutputStream());
      StringBuffer sb = <span style="color: #0000ff">new<span style="color: #000000"> StringBuffer();
      sb.append(PREFIX);
      sb.append(BOUNDARY);
      sb.append(LINE_END);
      <span style="color: #008000">/**<span style="color: #008000">
      • 这里重点注意: name里面的值为服务端需要key 只有这个key 才可以得到对应的文件
      • filename是文件的名字,包含后缀名的 比如:abc.png
        <span style="color: #008000">*/<span style="color: #000000">
        sb.append("Content-Disposition: form-data; name=\"uploadfile\"; filename=\""
        • file.getName() + "\"" +<span style="color: #000000"> LINE_END);
          sb.append("Content-Type: application/octet-stream; charset=" + CHARSET +<span style="color: #000000"> LINE_END);
          sb.append(LINE_END);
          dos.write(sb.toString().getBytes());
          InputStream is = <span style="color: #0000ff">new<span style="color: #000000"> FileInputStream(file);
          <span style="color: #0000ff">byte[] bytes = <span style="color: #0000ff">new <span style="color: #0000ff">byte[1024<span style="color: #000000">];
          <span style="color: #0000ff">int len = 0<span style="color: #000000">;
          <span style="color: #0000ff">while ((len = is.read(bytes)) != -1<span style="color: #000000">) {
          dos.write(bytes,0<span style="color: #000000">,len);
          }
          is.close();
          dos.write(LINE_END.getBytes());
          <span style="color: #0000ff">byte[] end_data = (PREFIX + BOUNDARY + PREFIX +<span style="color: #000000"> LINE_END).getBytes();
          dos.write(end_data);
          dos.flush();
          InputStream input =<span style="color: #000000"> conn.getInputStream();
          StringBuffer sb1 = <span style="color: #0000ff">new<span style="color: #000000"> StringBuffer();
          <span style="color: #0000ff">int<span style="color: #000000"> ss;
          <span style="color: #0000ff">while ((ss = input.read()) != -1<span style="color: #000000">) {
          sb1.append((<span style="color: #0000ff">char<span style="color: #000000">) ss);
          }
          result =<span style="color: #000000"> sb1.toString();
          }
          } <span style="color: #0000ff">catch<span style="color: #000000"> (MalformedURLException e) {
          e.printStackTrace();
          } <span style="color: #0000ff">catch<span style="color: #000000"> (IOException e) {
          e.printStackTrace();
          }
          <span style="color: #0000ff">return<span style="color: #000000"> result;
          }
          <span style="color: #008000">/**<span style="color: #008000">
    • 通过拼接的方式构造请求内容,实现参数传输以及文件传输
    • <span style="color: #808080">@param<span style="color: #008000"> url Service net address
    • <span style="color: #808080">@param<span style="color: #008000"> params text content
    • <span style="color: #808080">@param<span style="color: #008000"> files pictures
    • <span style="color: #808080">@return<span style="color: #008000"> String result of Service response
    • <span style="color: #808080">@throws<span style="color: #008000"> IOException
      <span style="color: #008000">/
      <span style="color: #0000ff">public <span style="color: #0000ff">static String post(String url,Map<String,String> params,File><span style="color: #000000"> files)
      <span style="color: #0000ff">throws<span style="color: #000000"> IOException {
      String BOUNDARY =<span style="color: #000000"> UUID.randomUUID().toString();
      String PREFIX = "--",LINEND = "\r\n"<span style="color: #000000">;
      String MULTIPART_FROM_DATA = "multipart/form-data"<span style="color: #000000">;
      String CHARSET = "UTF-8"<span style="color: #000000">;
      URL uri = <span style="color: #0000ff">new<span style="color: #000000"> URL(url);
      HttpURLConnection conn =<span style="color: #000000"> (HttpURLConnection) uri.openConnection();
      conn.setReadTimeout(10
      1000); <span style="color: #008000">//<span style="color: #008000"> 缓存的最长时间
      conn.setDoInput(<span style="color: #0000ff">true); <span style="color: #008000">//<span style="color: #008000"> 允许输入
      conn.setDoOutput(<span style="color: #0000ff">true); <span style="color: #008000">//<span style="color: #008000"> 允许输出
      conn.setUseCaches(<span style="color: #0000ff">false); <span style="color: #008000">//<span style="color: #008000"> 不允许使用缓存
      conn.setRequestMethod("POST"<span style="color: #000000">);
      conn.setRequestProperty("connection","keep-alive"<span style="color: #000000">);
      conn.setRequestProperty("Charsert","UTF-8"<span style="color: #000000">);
      conn.setRequestProperty("Content-Type",MULTIPART_FROM_DATA + ";boundary=" +<span style="color: #000000"> BOUNDARY);
      <span style="color: #008000">//<span style="color: #008000"> 首先组拼文本类型的参数
      StringBuilder sb = <span style="color: #0000ff">new<span style="color: #000000"> StringBuilder();
      <span style="color: #0000ff">for (Map.Entry<String,String><span style="color: #000000"> entry : params.entrySet()) {
      sb.append(PREFIX);
      sb.append(BOUNDARY);
      sb.append(LINEND);
      sb.append("Content-Disposition: form-data; name=\"" + entry.getKey() + "\"" +<span style="color: #000000"> LINEND);
      sb.append("Content-Type: text/plain; charset=" + CHARSET +<span style="color: #000000"> LINEND);
      sb.append("Content-Transfer-Encoding: 8bit" +<span style="color: #000000"> LINEND);
      sb.append(LINEND);
      sb.append(entry.getValue());
      sb.append(LINEND);
      }
      DataOutputStream outStream = <span style="color: #0000ff">new<span style="color: #000000"> DataOutputStream(conn.getOutputStream());
      outStream.write(sb.toString().getBytes());
      <span style="color: #008000">//<span style="color: #008000"> 发送文件数据
      <span style="color: #0000ff">if (files != <span style="color: #0000ff">null<span style="color: #000000">)
      <span style="color: #0000ff">for (Map.Entry<String,File><span style="color: #000000"> file : files.entrySet()) {
      StringBuilder sb1 = <span style="color: #0000ff">new<span style="color: #000000"> StringBuilder();
      sb1.append(PREFIX);
      sb1.append(BOUNDARY);
      sb1.append(LINEND);
      sb1.append("Content-Disposition: form-data; name=\"uploadfile\"; filename=\""
      • file.getValue().getName() + "\"" +<span style="color: #000000"> LINEND);
        sb1.append("Content-Type: application/octet-stream; charset=" + CHARSET +<span style="color: #000000"> LINEND);
        sb1.append(LINEND);
        outStream.write(sb1.toString().getBytes());
        InputStream is = <span style="color: #0000ff">new<span style="color: #000000"> FileInputStream(file.getValue());
        <span style="color: #0000ff">byte[] buffer = <span style="color: #0000ff">new <span style="color: #0000ff">byte[1024<span style="color: #000000">];
        <span style="color: #0000ff">int len = 0<span style="color: #000000">;
        <span style="color: #0000ff">while ((len = is.read(buffer)) != -1<span style="color: #000000">) {
        outStream.write(buffer,len);
        }
        is.close();
        outStream.write(LINEND.getBytes());
        }
        <span style="color: #0000ff">byte[] end_data = (PREFIX + BOUNDARY + PREFIX +<span style="color: #000000"> LINEND).getBytes();
        outStream.write(end_data);
        outStream.flush();
        <span style="color: #0000ff">int res =<span style="color: #000000"> conn.getResponseCode();
        InputStream in =<span style="color: #000000"> conn.getInputStream();
        StringBuilder sb2 = <span style="color: #0000ff">new<span style="color: #000000"> StringBuilder();
        <span style="color: #0000ff">if (res == 200<span style="color: #000000">) {
        <span style="color: #0000ff">int<span style="color: #000000"> ch;
        <span style="color: #0000ff">while ((ch = in.read()) != -1<span style="color: #000000">) {
        sb2.append((<span style="color: #0000ff">char<span style="color: #000000">) ch);
        }
        }
        outStream.close();
        conn.disconnect();
        <span style="color: #0000ff">return<span style="color: #000000"> sb2.toString();
        }
        <span style="color: #008000">//<span style="color: #008000"> 测试
        <span style="color: #0000ff">public <span style="color: #0000ff">static <span style="color: #0000ff">void main(String[] args) <span style="color: #0000ff">throws<span style="color: #000000"> IOException {
        String requestURL = "sss"<span style="color: #000000">;
        <span style="color: #0000ff">final Map<String,String> params = <span style="color: #0000ff">new HashMap<String,String><span style="color: #000000">();
        params.put("send_userId",String.valueOf(1<span style="color: #000000">));
        params.put("send_email","ss@ss.com"<span style="color: #000000">);
        <span style="color: #0000ff">final Map<String,File> files = <span style="color: #0000ff">new HashMap<String,File><span style="color: #000000">();
        files.put("uploadfile",<span style="color: #0000ff">new File("/var/data/de.jpg"<span style="color: #000000">));
        <span style="color: #0000ff">final String result =<span style="color: #000000"> UploadUtil.post(requestURL,params,files);
        System.out.println("result is: " +<span style="color: #000000"> result);
        }
        }

二、PHP服务端接收文件,临时保存并继续上传至java后端:

  1. 接收文件

PHP namespace App\Controller;

<span style="color: #0000ff">use<span style="color: #000000"> Action\RestAction;
<span style="color: #0000ff">use<span style="color: #000000"> Api\UploadApi;

<span style="color: #0000ff">class UserController <span style="color: #0000ff">extends<span style="color: #000000"> RestAction
{
<span style="color: #008000">/<span style="color: #008000">

  • 用户头像上传
    <span style="color: #008000">*/
    <span style="color: #0000ff">public <span style="color: #0000ff">function set_avatar_post(<span style="color: #800080">$code<span style="color: #000000">)
    {
    <span style="color: #800080">$uploadApi = <span style="color: #0000ff">new<span style="color: #000000"> UploadApi();
    <span style="color: #800080">$res = <span style="color: #800080">$uploadApi->uploads('avatar'<span style="color: #000000">);
    <span style="color: #800080">$filename = <span style="color: #800080">$res['data'<span style="color: #000000">];

    <span style="color: #800080">$result = <span style="color: #800080">$uploadApi->uploadAvatar(<span style="color: #800080">$code,<span style="color: #800080">$filename<span style="color: #000000">);
    @<span style="color: #008080">unlink(<span style="color: #800080">$filename); <span style="color: #008000">//<span style="color: #008000">删除图片
    <span style="color: #0000ff">if (!<span style="color: #800080">$result['status'<span style="color: #000000">]) {
    <span style="color: #800080">$this->response(<span style="color: #800080">$result<span style="color: #000000">);
    }
    <span style="color: #800080">$avatar = A("Personal","Api")->getAvatar(<span style="color: #800080">$code<span style="color: #000000">);
    <span style="color: #800080">$this->response(<span style="color: #800080">$avatar<span style="color: #000000">);
    }
    }

  2. 上传

PHP namespace Api\Action;

<span style="color: #0000ff">class<span style="color: #000000"> UploadApi
{
<span style="color: #0000ff">public <span style="color: #0000ff">function<span style="color: #000000"> __construct()
{
<span style="color: #008000">//<span style="color: #008000">...
<span style="color: #000000"> }

</span><span style="color: #0000ff"&gt;public</span> <span style="color: #0000ff"&gt;function</span> curlGet(<span style="color: #800080"&gt;$url</span>,<span style="color: #800080"&gt;$param</span> = <span style="color: #0000ff"&gt;array</span>(),<span style="color: #800080"&gt;$timeout</span> = 30,<span style="color: #800080"&gt;$ajaxResponseImmediately</span> = <span style="color: #0000ff"&gt;true</span><span style="color: #000000"&gt;)
{
    </span><span style="color: #800080"&gt;$opts</span> = <span style="color: #0000ff"&gt;array</span><span style="color: #000000"&gt;(
        CURLOPT_TIMEOUT </span>=> <span style="color: #800080"&gt;$timeout</span>,<span style="color: #000000"&gt;
        CURLOPT_RETURNTRANSFER </span>=> 1,<span style="color: #000000"&gt;
        CURLOPT_SSL_VERIFYPEER </span>=> <span style="color: #0000ff"&gt;false</span>,<span style="color: #000000"&gt;
        CURLOPT_SSL_VERIFYHOST </span>=> <span style="color: #0000ff"&gt;false</span>,<span style="color: #000000"&gt;
        CURLOPT_HTTPHEADER </span>=> <span style="color: #800080"&gt;$header</span><span style="color: #000000"&gt;
    );
    </span><span style="color: #0000ff"&gt;switch</span> (<span style="color: #008080"&gt;strtoupper</span>(<span style="color: #800080"&gt;$method</span><span style="color: #000000"&gt;)) {
        </span><span style="color: #008000"&gt;//</span><span style="color: #008000"&gt; case 'POST':
            // $opts[CURLOPT_URL] = $url;
            // $opts[CURLOPT_POST] = 1;
            // $opts[CURLOPT_POSTFIELDS] = $param;
            // break;</span>
        <span style="color: #0000ff"&gt;default</span>:
            <span style="color: #800080"&gt;$opts</span>[CURLOPT_URL] = <span style="color: #800080"&gt;$url</span> . '?' . <span style="color: #008080"&gt;http_build_query</span>(<span style="color: #800080"&gt;$param</span><span style="color: #000000"&gt;);
            </span><span style="color: #0000ff"&gt;break</span><span style="color: #000000"&gt;;
    }

    </span><span style="color: #800080"&gt;$ch</span> =<span style="color: #000000"&gt; curl_init();
    curl_setopt_array(</span><span style="color: #800080"&gt;$ch</span>,<span style="color: #800080"&gt;$opts</span><span style="color: #000000"&gt;);
    </span><span style="color: #800080"&gt;$result</span> = curl_exec(<span style="color: #800080"&gt;$ch</span><span style="color: #000000"&gt;);

    </span><span style="color: #008000"&gt;//</span><span style="color: #008000"&gt;记录请求日志</span>
    curl_close(<span style="color: #800080"&gt;$ch</span><span style="color: #000000"&gt;);
    </span><span style="color: #0000ff"&gt;return</span> <span style="color: #800080"&gt;$result</span><span style="color: #000000"&gt;;
}

</span><span style="color: #0000ff"&gt;public</span> <span style="color: #0000ff"&gt;function</span> curlPost(<span style="color: #800080"&gt;$url</span>,<span style="color: #000000"&gt;
        CURLOPT_HTTPHEADER </span>=> <span style="color: #800080"&gt;$header</span><span style="color: #000000"&gt;
    );
    </span><span style="color: #0000ff"&gt;switch</span> (<span style="color: #008080"&gt;strtoupper</span>(<span style="color: #800080"&gt;$method</span><span style="color: #000000"&gt;)) {
        </span><span style="color: #0000ff"&gt;case</span> 'POST':
        <span style="color: #0000ff"&gt;default</span>:
            <span style="color: #800080"&gt;$opts</span>[CURLOPT_URL] = <span style="color: #800080"&gt;$url</span><span style="color: #000000"&gt;;
            </span><span style="color: #800080"&gt;$opts</span>[CURLOPT_POST] = 1<span style="color: #000000"&gt;;
            </span><span style="color: #800080"&gt;$opts</span>[CURLOPT_POSTFIELDS] = <span style="color: #800080"&gt;$param</span><span style="color: #000000"&gt;;
            </span><span style="color: #0000ff"&gt;break</span><span style="color: #000000"&gt;;
            </span><span style="color: #008000"&gt;//</span><span style="color: #008000"&gt; $opts[CURLOPT_URL] = $url . '?' . http_build_query($param);
            // break;</span>

<span style="color: #000000"> }

    </span><span style="color: #800080"&gt;$ch</span> =<span style="color: #000000"&gt; curl_init();
    curl_setopt_array(</span><span style="color: #800080"&gt;$ch</span>,<span style="color: #800080"&gt;$opts</span><span style="color: #000000"&gt;);
    </span><span style="color: #800080"&gt;$result</span> = curl_exec(<span style="color: #800080"&gt;$ch</span><span style="color: #000000"&gt;);

    </span><span style="color: #800080"&gt;$log_data</span>['result'] = <span style="color: #800080"&gt;$result</span><span style="color: #000000"&gt;;
    </span><span style="color: #0000ff"&gt;if</span> (!<span style="color: #0000ff"&gt;empty</span>(<span style="color: #800080"&gt;$param</span>)) <span style="color: #800080"&gt;$log_data</span>['param'] = <span style="color: #800080"&gt;$param</span><span style="color: #000000"&gt;;
    curl_close(</span><span style="color: #800080"&gt;$ch</span><span style="color: #000000"&gt;);
    </span><span style="color: #0000ff"&gt;return</span> <span style="color: #800080"&gt;$result</span><span style="color: #000000"&gt;;
}

</span><span style="color: #0000ff"&gt;public</span> <span style="color: #0000ff"&gt;function</span> uploads(<span style="color: #800080"&gt;$param</span> = ''<span style="color: #000000"&gt;)
{
    </span><span style="color: #0000ff"&gt;if</span> (<span style="color: #800080"&gt;$param</span> == ''<span style="color: #000000"&gt;) {
        </span><span style="color: #800080"&gt;$param</span> = 'imgFile'<span style="color: #000000"&gt;;
    }
    </span><span style="color: #008000"&gt;//</span><span style="color: #008000"&gt; <a href="https://www.jb51.cc/tag/wenjian/" target="_blank" class="keywords">文件</a>保存目录路径</span>
    <span style="color: #800080"&gt;$save_url</span> = <span style="color: #008080"&gt;dirname</span>(<span style="color: #008080"&gt;dirname</span>(<span style="color: #008080"&gt;dirname</span>(<span style="color: #ff00ff"&gt;__FILE__</span>))) . DIRECTORY_SEPARATOR . "Uploads" .<span style="color: #000000"&gt; DIRECTORY_SEPARATOR;
    </span><span style="color: #008000"&gt;//</span><span style="color: #008000"&gt; 定义允许<a href="https://www.jb51.cc/tag/shangchuan/" target="_blank" class="keywords">上传</a>的<a href="https://www.jb51.cc/tag/wenjian/" target="_blank" class="keywords">文件</a>扩展名</span>
    <span style="color: #800080"&gt;$ext_arr</span> = <span style="color: #0000ff"&gt;array</span><span style="color: #000000"&gt;(
        </span>'image' => <span style="color: #0000ff"&gt;array</span>('gif','jpg','jpeg','png','bmp'),<span style="color: #000000"&gt;
    );
    </span><span style="color: #008000"&gt;//</span><span style="color: #008000"&gt; 最大<a href="https://www.jb51.cc/tag/wenjian/" target="_blank" class="keywords">文件</a>大小</span>
    <span style="color: #800080"&gt;$max_size</span> = 20 * 1024<span style="color: #000000"&gt;;
    </span><span style="color: #008000"&gt;//</span><span style="color: #008000"&gt; <a href="https://www.jb51.cc/tag/PHP/" target="_blank" class="keywords">PHP</a><a href="https://www.jb51.cc/tag/shangchuan/" target="_blank" class="keywords">上传</a>失败</span>
    <span style="color: #0000ff"&gt;if</span> (!<span style="color: #0000ff"&gt;empty</span> (<span style="color: #800080"&gt;$_FILES</span> [<span style="color: #800080"&gt;$param</span>] ['error'<span style="color: #000000"&gt;])) {
        </span><span style="color: #0000ff"&gt;switch</span> (<span style="color: #800080"&gt;$_FILES</span> [<span style="color: #800080"&gt;$param</span>] ['error'<span style="color: #000000"&gt;]) {
            </span><span style="color: #0000ff"&gt;case</span> '1' :
                <span style="color: #800080"&gt;$error</span> = '超过<a href="https://www.jb51.cc/tag/PHP/" target="_blank" class="keywords">PHP</a>.ini允许的大小。'<span style="color: #000000"&gt;;
                </span><span style="color: #0000ff"&gt;break</span><span style="color: #000000"&gt;;
            </span><span style="color: #0000ff"&gt;case</span> '2' :
                <span style="color: #800080"&gt;$error</span> = '超过表单允许的大小。'<span style="color: #000000"&gt;;
                </span><span style="color: #0000ff"&gt;break</span><span style="color: #000000"&gt;;
            </span><span style="color: #0000ff"&gt;case</span> '3' :
                <span style="color: #800080"&gt;$error</span> = '<a href="https://www.jb51.cc/tag/tupian/" target="_blank" class="keywords">图片</a>只有部分被<a href="https://www.jb51.cc/tag/shangchuan/" target="_blank" class="keywords">上传</a>。'<span style="color: #000000"&gt;;
                </span><span style="color: #0000ff"&gt;break</span><span style="color: #000000"&gt;;
            </span><span style="color: #0000ff"&gt;case</span> '4' :
                <span style="color: #800080"&gt;$error</span> = '请选择<a href="https://www.jb51.cc/tag/tupian/" target="_blank" class="keywords">图片</a>。'<span style="color: #000000"&gt;;
                </span><span style="color: #0000ff"&gt;break</span><span style="color: #000000"&gt;;
            </span><span style="color: #0000ff"&gt;case</span> '6' :
                <span style="color: #800080"&gt;$error</span> = '找不到临时目录。'<span style="color: #000000"&gt;;
                </span><span style="color: #0000ff"&gt;break</span><span style="color: #000000"&gt;;
            </span><span style="color: #0000ff"&gt;case</span> '7' :
                <span style="color: #800080"&gt;$error</span> = '写<a href="https://www.jb51.cc/tag/wenjian/" target="_blank" class="keywords">文件</a>到硬盘出错。'<span style="color: #000000"&gt;;
                </span><span style="color: #0000ff"&gt;break</span><span style="color: #000000"&gt;;
            </span><span style="color: #0000ff"&gt;case</span> '8' :
                <span style="color: #800080"&gt;$error</span> = 'File upload stopped by extension。'<span style="color: #000000"&gt;;
                </span><span style="color: #0000ff"&gt;break</span><span style="color: #000000"&gt;;
            </span><span style="color: #0000ff"&gt;case</span> '999' :
            <span style="color: #0000ff"&gt;default</span> :
                <span style="color: #800080"&gt;$error</span> = '未知<a href="https://www.jb51.cc/tag/cuowu/" target="_blank" class="keywords">错误</a>。'<span style="color: #000000"&gt;;
        }
        </span><span style="color: #800080"&gt;$result</span> = <span style="color: #0000ff"&gt;array</span>('status' => '0','error' => '111111','msg' => <span style="color: #800080"&gt;$error</span><span style="color: #000000"&gt;);

    }
    </span><span style="color: #008000"&gt;//</span><span style="color: #008000"&gt; 有<a href="https://www.jb51.cc/tag/shangchuan/" target="_blank" class="keywords">上传</a><a href="https://www.jb51.cc/tag/wenjian/" target="_blank" class="keywords">文件</a>时</span>
    <span style="color: #0000ff"&gt;if</span> (<span style="color: #0000ff"&gt;empty</span> (<span style="color: #800080"&gt;$_FILES</span>) === <span style="color: #0000ff"&gt;false</span><span style="color: #000000"&gt;) {
        </span><span style="color: #800080"&gt;$file_name</span> = <span style="color: #800080"&gt;$_FILES</span> [<span style="color: #800080"&gt;$param</span>] ['name'];<span style="color: #008000"&gt;//</span><span style="color: #008000"&gt; 原<a href="https://www.jb51.cc/tag/wenjian/" target="_blank" class="keywords">文件</a>名</span>
        <span style="color: #800080"&gt;$tmp_name</span> = <span style="color: #800080"&gt;$_FILES</span> [<span style="color: #800080"&gt;$param</span>] ['tmp_name'];<span style="color: #008000"&gt;//</span><span style="color: #008000"&gt; 服务器上临时<a href="https://www.jb51.cc/tag/wenjian/" target="_blank" class="keywords">文件</a>名</span>
        <span style="color: #800080"&gt;$file_size</span> = <span style="color: #800080"&gt;$_FILES</span> [<span style="color: #800080"&gt;$param</span>] ['size'];<span style="color: #008000"&gt;//</span><span style="color: #008000"&gt; <a href="https://www.jb51.cc/tag/wenjian/" target="_blank" class="keywords">文件</a>大小
        // 检查<a href="https://www.jb51.cc/tag/wenjian/" target="_blank" class="keywords">文件</a>名</span>
        <span style="color: #0000ff"&gt;if</span> (!<span style="color: #800080"&gt;$file_name</span><span style="color: #000000"&gt;) {
            </span><span style="color: #800080"&gt;$result</span> = <span style="color: #0000ff"&gt;array</span>('status' => '0','msg' => '请选择<a href="https://www.jb51.cc/tag/wenjian/" target="_blank" class="keywords">文件</a>'<span style="color: #000000"&gt;);
        }
        </span><span style="color: #008000"&gt;//</span><span style="color: #008000"&gt; 检查是否已<a href="https://www.jb51.cc/tag/shangchuan/" target="_blank" class="keywords">上传</a></span>
        <span style="color: #0000ff"&gt;if</span> (@<span style="color: #008080"&gt;is_uploaded_file</span>(<span style="color: #800080"&gt;$tmp_name</span>) === <span style="color: #0000ff"&gt;false</span><span style="color: #000000"&gt;) {
            </span><span style="color: #800080"&gt;$result</span> = <span style="color: #0000ff"&gt;array</span>('status' => '0','msg' => '<a href="https://www.jb51.cc/tag/shangchuan/" target="_blank" class="keywords">上传</a>失败'<span style="color: #000000"&gt;);
        }
        </span><span style="color: #008000"&gt;//</span><span style="color: #008000"&gt; 检查<a href="https://www.jb51.cc/tag/wenjian/" target="_blank" class="keywords">文件</a>大小</span>
        <span style="color: #0000ff"&gt;if</span> (<span style="color: #800080"&gt;$file_size</span> > <span style="color: #800080"&gt;$max_size</span><span style="color: #000000"&gt;) {
            </span><span style="color: #800080"&gt;$result</span> = <span style="color: #0000ff"&gt;array</span>('status' => '0','msg' => ''<span style="color: #000000"&gt;);
        }
        </span><span style="color: #008000"&gt;//</span><span style="color: #008000"&gt; 检查目录名</span>
        <span style="color: #800080"&gt;$dir_name</span> = <span style="color: #0000ff"&gt;empty</span> (<span style="color: #800080"&gt;$_GET</span> ['dir']) ? 'image' : <span style="color: #008080"&gt;trim</span>(<span style="color: #800080"&gt;$_GET</span> ['dir'<span style="color: #000000"&gt;]);
        </span><span style="color: #0000ff"&gt;if</span> (<span style="color: #0000ff"&gt;empty</span> (<span style="color: #800080"&gt;$ext_arr</span> [<span style="color: #800080"&gt;$dir_name</span><span style="color: #000000"&gt;])) {
            </span><span style="color: #800080"&gt;$result</span> = <span style="color: #0000ff"&gt;array</span>('status' => '0','msg' => '目录名不正确'<span style="color: #000000"&gt;);
        }
        </span><span style="color: #008000"&gt;//</span><span style="color: #008000"&gt; 获得<a href="https://www.jb51.cc/tag/wenjian/" target="_blank" class="keywords">文件</a>扩展名</span>
        <span style="color: #800080"&gt;$temp_arr</span> = <span style="color: #008080"&gt;explode</span>('.',<span style="color: #800080"&gt;$file_name</span><span style="color: #000000"&gt;);
        </span><span style="color: #800080"&gt;$file_ext</span> = <span style="color: #008080"&gt;array_pop</span>(<span style="color: #800080"&gt;$temp_arr</span><span style="color: #000000"&gt;);
        </span><span style="color: #800080"&gt;$file_ext</span> = <span style="color: #008080"&gt;trim</span>(<span style="color: #800080"&gt;$file_ext</span><span style="color: #000000"&gt;);
        </span><span style="color: #800080"&gt;$file_ext</span> = <span style="color: #008080"&gt;strtolower</span>(<span style="color: #800080"&gt;$file_ext</span><span style="color: #000000"&gt;);
        </span><span style="color: #008000"&gt;//</span><span style="color: #008000"&gt; 检查扩展名</span>
        <span style="color: #0000ff"&gt;if</span> (<span style="color: #008080"&gt;in_array</span>(<span style="color: #800080"&gt;$file_ext</span>,<span style="color: #800080"&gt;$ext_arr</span> [<span style="color: #800080"&gt;$dir_name</span>]) === <span style="color: #0000ff"&gt;false</span><span style="color: #000000"&gt;) {
            </span><span style="color: #800080"&gt;$result</span> = <span style="color: #0000ff"&gt;array</span>('status' => '0','msg' => '<a href="https://www.jb51.cc/tag/shangchuan/" target="_blank" class="keywords">上传</a><a href="https://www.jb51.cc/tag/wenjian/" target="_blank" class="keywords">文件</a>扩展名是不允许的扩展名'<span style="color: #000000"&gt;);
        }
        </span><span style="color: #008000"&gt;//</span><span style="color: #008000"&gt; 创建<a href="https://www.jb51.cc/tag/wenjian/" target="_blank" class="keywords">文件</a>夹</span>
        <span style="color: #0000ff"&gt;if</span> (<span style="color: #800080"&gt;$dir_name</span> !== ''<span style="color: #000000"&gt;) {
            </span><span style="color: #0000ff"&gt;if</span> (!<span style="color: #008080"&gt;file_exists</span>(<span style="color: #800080"&gt;$save_url</span><span style="color: #000000"&gt;)) {
                </span><span style="color: #008080"&gt;mkdir</span>(<span style="color: #800080"&gt;$save_url</span><span style="color: #000000"&gt;);
            }
        }
        </span><span style="color: #800080"&gt;$new_file_name</span> = <span style="color: #008080"&gt;date</span>('YmdHis') . '_' . <span style="color: #008080"&gt;rand</span>(10000,99999) . '.' . <span style="color: #800080"&gt;$file_ext</span><span style="color: #000000"&gt;;
        </span><span style="color: #800080"&gt;$file_path</span> = <span style="color: #800080"&gt;$save_url</span> . <span style="color: #800080"&gt;$new_file_name</span><span style="color: #000000"&gt;;
        </span><span style="color: #0000ff"&gt;if</span> (<span style="color: #008080"&gt;move_uploaded_file</span>(<span style="color: #800080"&gt;$tmp_name</span>,<span style="color: #800080"&gt;$file_path</span>) === <span style="color: #0000ff"&gt;false</span><span style="color: #000000"&gt;) {
            </span><span style="color: #800080"&gt;$result</span>['msg'] = '<a href="https://www.jb51.cc/tag/shangchuan/" target="_blank" class="keywords">上传</a><a href="https://www.jb51.cc/tag/wenjian/" target="_blank" class="keywords">文件</a>失败'<span style="color: #000000"&gt;;
            </span><span style="color: #800080"&gt;$result</span> = <span style="color: #0000ff"&gt;array</span>('status' => '0','msg' => '<a href="https://www.jb51.cc/tag/shangchuan/" target="_blank" class="keywords">上传</a><a href="https://www.jb51.cc/tag/wenjian/" target="_blank" class="keywords">文件</a>失败'<span style="color: #000000"&gt;);
        } </span><span style="color: #0000ff"&gt;else</span><span style="color: #000000"&gt; {
            </span><span style="color: #800080"&gt;$result</span> = <span style="color: #0000ff"&gt;array</span>('status' => '1','error' => '000000','data' => <span style="color: #800080"&gt;$file_path</span><span style="color: #000000"&gt;);
        }
        @</span><span style="color: #008080"&gt;chmod</span>(<span style="color: #800080"&gt;$file_path</span>,0644<span style="color: #000000"&gt;);
        </span><span style="color: #0000ff"&gt;return</span> <span style="color: #800080"&gt;$result</span><span style="color: #000000"&gt;;
    }
}

</span><span style="color: #0000ff"&gt;public</span> <span style="color: #0000ff"&gt;function</span> uploadAvatar(<span style="color: #800080"&gt;$code</span>,<span style="color: #800080"&gt;$avatarImageName</span><span style="color: #000000"&gt;) {
    </span><span style="color: #800080"&gt;$url</span> = <span style="color: #800080"&gt;$this</span>->getApiUrl(<span style="color: #ff00ff"&gt;__METHOD__</span><span style="color: #000000"&gt;);
    </span><span style="color: #800080"&gt;$data</span> = <span style="color: #0000ff"&gt;array</span><span style="color: #000000"&gt;(
        </span>"code" => <span style="color: #800080"&gt;$code</span>,"ip" => <span style="color: #800080"&gt;$this</span>->params['ip'],"avatar" => !<span style="color: #0000ff"&gt;empty</span>(<span style="color: #800080"&gt;$avatarImageName</span>) ? '@' . <span style="color: #800080"&gt;$avatarImageName</span> : '',<span style="color: #000000"&gt;
    );
    </span><span style="color: #800080"&gt;$result</span> = <span style="color: #800080"&gt;$this</span>->curlPost(<span style="color: #800080"&gt;$url</span>,<span style="color: #800080"&gt;$data</span><span style="color: #000000"&gt;);
    </span><span style="color: #0000ff"&gt;return</span> <span style="color: #800080"&gt;$result</span><span style="color: #000000"&gt;;
}

}

  这样,PHP就已经接收到了来自客户端的 图片上传了,并且已经上传到java后端服务器。

  注意:这里有个坑,即PHP版本大于5.6以后,直接使用 @ 符号无法上传文件了,需要 加上一个安全选项:CURLOPT_SAFE_UPLOAD => false 才可以,或者使用5.6以的高级上传上传文件

,CURLOPT_POSTFIELDS,'file' => CURLFile(('image.png')),

三、java后端接收PHP上传图片

<span style="color: #0000ff">import<span style="color: #000000"> com.xx.core.pojo.Constants;
<span style="color: #0000ff">import<span style="color: #000000"> com.xx.core.pojo.MicroException;
<span style="color: #0000ff">import<span style="color: #000000"> com.xx.core.pojo.ResponseEntity;
<span style="color: #0000ff">import<span style="color: #000000"> com.xx.core.web.spring.bind.annotation.ClientIP;
<span style="color: #0000ff">import<span style="color: #000000"> com.xx.core.web.spring.bind.annotation.SessionUserId;
<span style="color: #0000ff">import<span style="color: #000000"> com.xx.c.pojo.user.UpFileUrlBean;
<span style="color: #0000ff">import<span style="color: #000000"> com.xx.c.service.user.UserService;
<span style="color: #0000ff">import<span style="color: #000000"> org.springframework.stereotype.Controller;
<span style="color: #0000ff">import<span style="color: #000000"> org.springframework.web.bind.annotation.ModelAttribute;
<span style="color: #0000ff">import<span style="color: #000000"> org.springframework.web.bind.annotation.RequestMapping;
<span style="color: #0000ff">import<span style="color: #000000"> org.springframework.web.bind.annotation.RequestMethod;
<span style="color: #0000ff">import<span style="color: #000000"> org.springframework.web.bind.annotation.RequestParam;
<span style="color: #0000ff">import<span style="color: #000000"> org.springframework.web.bind.annotation.ResponseBody;
<span style="color: #0000ff">import<span style="color: #000000"> org.springframework.web.multipart.MultipartFile;
<span style="color: #0000ff">import<span style="color: #000000"> org.springframework.web.multipart.MultipartHttpServletRequest;

<span style="color: #0000ff">import<span style="color: #000000"> javax.annotation.Resource;
<span style="color: #0000ff">import<span style="color: #000000"> javax.servlet.http.HttpServletRequest;
<span style="color: #0000ff">import<span style="color: #000000"> java.util.Iterator;

@Controller
@RequestMapping(value = "upload"<span style="color: #000000">)
<span style="color: #0000ff">public <span style="color: #0000ff">class<span style="color: #000000"> UploadAction {

@Resource(name </span>= "userService"<span style="color: #000000"&gt;)
</span><span style="color: #0000ff"&gt;private</span><span style="color: #000000"&gt; UserService userService;

@RequestMapping(value </span>= "/uploadAvatar",method = RequestMethod.POST,produces = "application/json"<span style="color: #000000"&gt;)
@ResponseBody
</span><span style="color: #0000ff"&gt;public</span><span style="color: #000000"&gt; Object uploadAvatar(@RequestParam String code,@ClientIP String addIp,@SessionUserId Long userId,<a href="https://www.jb51.cc/tag/modelattribute/" target="_blank" class="keywords">@modelattribute</a> UpFileUrlBean bean,HttpServletRequest request) </span><span style="color: #0000ff"&gt;throws</span><span style="color: #000000"&gt; MicroException {
    bean.setAddIp(addIp);
    bean.setUserId(userId);

    </span><span style="color: #0000ff"&gt;try</span><span style="color: #000000"&gt; {
        </span><span style="color: #008000"&gt;//</span><span style="color: #008000"&gt; 转型为MultipartHttpRequest:</span>
        MultipartHttpServletRequest multipartRequest =<span style="color: #000000"&gt; (MultipartHttpServletRequest) request;
        </span><span style="color: #008000"&gt;//</span><span style="color: #008000"&gt; 从其中取出一个<a href="https://www.jb51.cc/tag/wenjian/" target="_blank" class="keywords">文件</a> 后续可使用spring <a href="https://www.jb51.cc/tag/shangchuan/" target="_blank" class="keywords">上传</a><a href="https://www.jb51.cc/tag/wenjian/" target="_blank" class="keywords">文件</a><a href="https://www.jb51.cc/tag/fangfa/" target="_blank" class="keywords">方法</a>:file.transferTo(destFile);</span>
        MultipartFile file = <span style="color: #0000ff"&gt;null</span><span style="color: #000000"&gt;;
        </span><span style="color: #0000ff"&gt;for</span> (Iterator<String> it =<span style="color: #000000"&gt; multipartRequest.getFileNames(); it.hasNext();) {
            file </span>=<span style="color: #000000"&gt; multipartRequest.getFile((String) it.next());
        }
        userService.uploadAvatar(file,bean);
    } </span><span style="color: #0000ff"&gt;catch</span><span style="color: #000000"&gt; (Exception e) {
        </span><span style="color: #0000ff"&gt;throw</span> <span style="color: #0000ff"&gt;new</span><span style="color: #000000"&gt; MicroException(Constants.ErrCode.UPLOAD_AVATAR_TO_SERVER_<a href="https://www.jb51.cc/tag/Failed/" target="_blank" class="keywords">Failed</a>,Constants.ErrMsg.UPLOAD_AVATAR_TO_SERVER_<a href="https://www.jb51.cc/tag/Failed/" target="_blank" class="keywords">Failed</a>,e);
    }

    ResponseEntity ret </span>= <span style="color: #0000ff"&gt;new</span><span style="color: #000000"&gt; ResponseEntity(Constants.System.OK);
    </span><span style="color: #0000ff"&gt;return</span><span style="color: #000000"&gt; ret;
}

}

  至此,上传流程已经完成了。(当然,后续还可能使用其他上传,比如dubbo调用文件系统上传文件调用第三方sdk上传文件服务器。。。, 原理大抵一样,使用字节流进行传输,然后读取出来存储到文件

  一般为app写的接口中,都会涉及到加解密问题,此时,文件不应该算作加密的范畴,而应单独给一个字段。

原文链接:https://www.f2er.com/php/74357.html

猜你在找的PHP相关文章