在现在的网络开发中,上传图片类的需求实在是太普通不过了,但是对于怎么样做到上传图片,对于刚开始建立项目的时候,还是有点不知所措的。也许有幸,我们做的项目是之前已经有人写过类似的用例了,那么我们只需要依葫芦画瓢就行了。
好好了解下图片上传(文件上传)的方式,对于认知的提升还是有好处的。而且说不定哪天你就有个这样的需求呢,这里是一条龙上传。
本文就一个从app到PHP层,再到java层的流程,演译下整个上传图片的流程吧。
一、app端获取用户选择的图片,转化为输入流,上传至PHP前端接口:
<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">
- file.getName() + "\"" +<span style="color: #000000"> LINE_END);
- 通过拼接的方式构造请求内容,实现参数传输以及文件传输
- <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);
}
}
- file.getValue().getName() + "\"" +<span style="color: #000000"> LINEND);
二、PHP服务端接收文件,临时保存并继续上传至java后端:
1. 接收文件类
<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. 上传类
{
<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">public</span> <span style="color: #0000ff">function</span> curlGet(<span style="color: #800080">$url</span>,<span style="color: #800080">$param</span> = <span style="color: #0000ff">array</span>(),<span style="color: #800080">$timeout</span> = 30,<span style="color: #800080">$ajaxResponseImmediately</span> = <span style="color: #0000ff">true</span><span style="color: #000000">)
{
</span><span style="color: #800080">$opts</span> = <span style="color: #0000ff">array</span><span style="color: #000000">(
CURLOPT_TIMEOUT </span>=> <span style="color: #800080">$timeout</span>,<span style="color: #000000">
CURLOPT_RETURNTRANSFER </span>=> 1,<span style="color: #000000">
CURLOPT_SSL_VERIFYPEER </span>=> <span style="color: #0000ff">false</span>,<span style="color: #000000">
CURLOPT_SSL_VERIFYHOST </span>=> <span style="color: #0000ff">false</span>,<span style="color: #000000">
CURLOPT_HTTPHEADER </span>=> <span style="color: #800080">$header</span><span style="color: #000000">
);
</span><span style="color: #0000ff">switch</span> (<span style="color: #008080">strtoupper</span>(<span style="color: #800080">$method</span><span style="color: #000000">)) {
</span><span style="color: #008000">//</span><span style="color: #008000"> case 'POST':
// $opts[CURLOPT_URL] = $url;
// $opts[CURLOPT_POST] = 1;
// $opts[CURLOPT_POSTFIELDS] = $param;
// break;</span>
<span style="color: #0000ff">default</span>:
<span style="color: #800080">$opts</span>[CURLOPT_URL] = <span style="color: #800080">$url</span> . '?' . <span style="color: #008080">http_build_query</span>(<span style="color: #800080">$param</span><span style="color: #000000">);
</span><span style="color: #0000ff">break</span><span style="color: #000000">;
}
</span><span style="color: #800080">$ch</span> =<span style="color: #000000"> curl_init();
curl_setopt_array(</span><span style="color: #800080">$ch</span>,<span style="color: #800080">$opts</span><span style="color: #000000">);
</span><span style="color: #800080">$result</span> = curl_exec(<span style="color: #800080">$ch</span><span style="color: #000000">);
</span><span style="color: #008000">//</span><span style="color: #008000">记录请求日志</span>
curl_close(<span style="color: #800080">$ch</span><span style="color: #000000">);
</span><span style="color: #0000ff">return</span> <span style="color: #800080">$result</span><span style="color: #000000">;
}
</span><span style="color: #0000ff">public</span> <span style="color: #0000ff">function</span> curlPost(<span style="color: #800080">$url</span>,<span style="color: #000000">
CURLOPT_HTTPHEADER </span>=> <span style="color: #800080">$header</span><span style="color: #000000">
);
</span><span style="color: #0000ff">switch</span> (<span style="color: #008080">strtoupper</span>(<span style="color: #800080">$method</span><span style="color: #000000">)) {
</span><span style="color: #0000ff">case</span> 'POST':
<span style="color: #0000ff">default</span>:
<span style="color: #800080">$opts</span>[CURLOPT_URL] = <span style="color: #800080">$url</span><span style="color: #000000">;
</span><span style="color: #800080">$opts</span>[CURLOPT_POST] = 1<span style="color: #000000">;
</span><span style="color: #800080">$opts</span>[CURLOPT_POSTFIELDS] = <span style="color: #800080">$param</span><span style="color: #000000">;
</span><span style="color: #0000ff">break</span><span style="color: #000000">;
</span><span style="color: #008000">//</span><span style="color: #008000"> $opts[CURLOPT_URL] = $url . '?' . http_build_query($param);
// break;</span>
<span style="color: #000000"> }
</span><span style="color: #800080">$ch</span> =<span style="color: #000000"> curl_init();
curl_setopt_array(</span><span style="color: #800080">$ch</span>,<span style="color: #800080">$opts</span><span style="color: #000000">);
</span><span style="color: #800080">$result</span> = curl_exec(<span style="color: #800080">$ch</span><span style="color: #000000">);
</span><span style="color: #800080">$log_data</span>['result'] = <span style="color: #800080">$result</span><span style="color: #000000">;
</span><span style="color: #0000ff">if</span> (!<span style="color: #0000ff">empty</span>(<span style="color: #800080">$param</span>)) <span style="color: #800080">$log_data</span>['param'] = <span style="color: #800080">$param</span><span style="color: #000000">;
curl_close(</span><span style="color: #800080">$ch</span><span style="color: #000000">);
</span><span style="color: #0000ff">return</span> <span style="color: #800080">$result</span><span style="color: #000000">;
}
</span><span style="color: #0000ff">public</span> <span style="color: #0000ff">function</span> uploads(<span style="color: #800080">$param</span> = ''<span style="color: #000000">)
{
</span><span style="color: #0000ff">if</span> (<span style="color: #800080">$param</span> == ''<span style="color: #000000">) {
</span><span style="color: #800080">$param</span> = 'imgFile'<span style="color: #000000">;
}
</span><span style="color: #008000">//</span><span style="color: #008000"> <a href="https://www.jb51.cc/tag/wenjian/" target="_blank" class="keywords">文件</a>保存目录路径</span>
<span style="color: #800080">$save_url</span> = <span style="color: #008080">dirname</span>(<span style="color: #008080">dirname</span>(<span style="color: #008080">dirname</span>(<span style="color: #ff00ff">__FILE__</span>))) . DIRECTORY_SEPARATOR . "Uploads" .<span style="color: #000000"> DIRECTORY_SEPARATOR;
</span><span style="color: #008000">//</span><span style="color: #008000"> 定义允许<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">$ext_arr</span> = <span style="color: #0000ff">array</span><span style="color: #000000">(
</span>'image' => <span style="color: #0000ff">array</span>('gif','jpg','jpeg','png','bmp'),<span style="color: #000000">
);
</span><span style="color: #008000">//</span><span style="color: #008000"> 最大<a href="https://www.jb51.cc/tag/wenjian/" target="_blank" class="keywords">文件</a>大小</span>
<span style="color: #800080">$max_size</span> = 20 * 1024<span style="color: #000000">;
</span><span style="color: #008000">//</span><span style="color: #008000"> <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">if</span> (!<span style="color: #0000ff">empty</span> (<span style="color: #800080">$_FILES</span> [<span style="color: #800080">$param</span>] ['error'<span style="color: #000000">])) {
</span><span style="color: #0000ff">switch</span> (<span style="color: #800080">$_FILES</span> [<span style="color: #800080">$param</span>] ['error'<span style="color: #000000">]) {
</span><span style="color: #0000ff">case</span> '1' :
<span style="color: #800080">$error</span> = '超过<a href="https://www.jb51.cc/tag/PHP/" target="_blank" class="keywords">PHP</a>.ini允许的大小。'<span style="color: #000000">;
</span><span style="color: #0000ff">break</span><span style="color: #000000">;
</span><span style="color: #0000ff">case</span> '2' :
<span style="color: #800080">$error</span> = '超过表单允许的大小。'<span style="color: #000000">;
</span><span style="color: #0000ff">break</span><span style="color: #000000">;
</span><span style="color: #0000ff">case</span> '3' :
<span style="color: #800080">$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">;
</span><span style="color: #0000ff">break</span><span style="color: #000000">;
</span><span style="color: #0000ff">case</span> '4' :
<span style="color: #800080">$error</span> = '请选择<a href="https://www.jb51.cc/tag/tupian/" target="_blank" class="keywords">图片</a>。'<span style="color: #000000">;
</span><span style="color: #0000ff">break</span><span style="color: #000000">;
</span><span style="color: #0000ff">case</span> '6' :
<span style="color: #800080">$error</span> = '找不到临时目录。'<span style="color: #000000">;
</span><span style="color: #0000ff">break</span><span style="color: #000000">;
</span><span style="color: #0000ff">case</span> '7' :
<span style="color: #800080">$error</span> = '写<a href="https://www.jb51.cc/tag/wenjian/" target="_blank" class="keywords">文件</a>到硬盘出错。'<span style="color: #000000">;
</span><span style="color: #0000ff">break</span><span style="color: #000000">;
</span><span style="color: #0000ff">case</span> '8' :
<span style="color: #800080">$error</span> = 'File upload stopped by extension。'<span style="color: #000000">;
</span><span style="color: #0000ff">break</span><span style="color: #000000">;
</span><span style="color: #0000ff">case</span> '999' :
<span style="color: #0000ff">default</span> :
<span style="color: #800080">$error</span> = '未知<a href="https://www.jb51.cc/tag/cuowu/" target="_blank" class="keywords">错误</a>。'<span style="color: #000000">;
}
</span><span style="color: #800080">$result</span> = <span style="color: #0000ff">array</span>('status' => '0','error' => '111111','msg' => <span style="color: #800080">$error</span><span style="color: #000000">);
}
</span><span style="color: #008000">//</span><span style="color: #008000"> 有<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">if</span> (<span style="color: #0000ff">empty</span> (<span style="color: #800080">$_FILES</span>) === <span style="color: #0000ff">false</span><span style="color: #000000">) {
</span><span style="color: #800080">$file_name</span> = <span style="color: #800080">$_FILES</span> [<span style="color: #800080">$param</span>] ['name'];<span style="color: #008000">//</span><span style="color: #008000"> 原<a href="https://www.jb51.cc/tag/wenjian/" target="_blank" class="keywords">文件</a>名</span>
<span style="color: #800080">$tmp_name</span> = <span style="color: #800080">$_FILES</span> [<span style="color: #800080">$param</span>] ['tmp_name'];<span style="color: #008000">//</span><span style="color: #008000"> 服务器上临时<a href="https://www.jb51.cc/tag/wenjian/" target="_blank" class="keywords">文件</a>名</span>
<span style="color: #800080">$file_size</span> = <span style="color: #800080">$_FILES</span> [<span style="color: #800080">$param</span>] ['size'];<span style="color: #008000">//</span><span style="color: #008000"> <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">if</span> (!<span style="color: #800080">$file_name</span><span style="color: #000000">) {
</span><span style="color: #800080">$result</span> = <span style="color: #0000ff">array</span>('status' => '0','msg' => '请选择<a href="https://www.jb51.cc/tag/wenjian/" target="_blank" class="keywords">文件</a>'<span style="color: #000000">);
}
</span><span style="color: #008000">//</span><span style="color: #008000"> 检查是否已<a href="https://www.jb51.cc/tag/shangchuan/" target="_blank" class="keywords">上传</a></span>
<span style="color: #0000ff">if</span> (@<span style="color: #008080">is_uploaded_file</span>(<span style="color: #800080">$tmp_name</span>) === <span style="color: #0000ff">false</span><span style="color: #000000">) {
</span><span style="color: #800080">$result</span> = <span style="color: #0000ff">array</span>('status' => '0','msg' => '<a href="https://www.jb51.cc/tag/shangchuan/" target="_blank" class="keywords">上传</a>失败'<span style="color: #000000">);
}
</span><span style="color: #008000">//</span><span style="color: #008000"> 检查<a href="https://www.jb51.cc/tag/wenjian/" target="_blank" class="keywords">文件</a>大小</span>
<span style="color: #0000ff">if</span> (<span style="color: #800080">$file_size</span> > <span style="color: #800080">$max_size</span><span style="color: #000000">) {
</span><span style="color: #800080">$result</span> = <span style="color: #0000ff">array</span>('status' => '0','msg' => ''<span style="color: #000000">);
}
</span><span style="color: #008000">//</span><span style="color: #008000"> 检查目录名</span>
<span style="color: #800080">$dir_name</span> = <span style="color: #0000ff">empty</span> (<span style="color: #800080">$_GET</span> ['dir']) ? 'image' : <span style="color: #008080">trim</span>(<span style="color: #800080">$_GET</span> ['dir'<span style="color: #000000">]);
</span><span style="color: #0000ff">if</span> (<span style="color: #0000ff">empty</span> (<span style="color: #800080">$ext_arr</span> [<span style="color: #800080">$dir_name</span><span style="color: #000000">])) {
</span><span style="color: #800080">$result</span> = <span style="color: #0000ff">array</span>('status' => '0','msg' => '目录名不正确'<span style="color: #000000">);
}
</span><span style="color: #008000">//</span><span style="color: #008000"> 获得<a href="https://www.jb51.cc/tag/wenjian/" target="_blank" class="keywords">文件</a>扩展名</span>
<span style="color: #800080">$temp_arr</span> = <span style="color: #008080">explode</span>('.',<span style="color: #800080">$file_name</span><span style="color: #000000">);
</span><span style="color: #800080">$file_ext</span> = <span style="color: #008080">array_pop</span>(<span style="color: #800080">$temp_arr</span><span style="color: #000000">);
</span><span style="color: #800080">$file_ext</span> = <span style="color: #008080">trim</span>(<span style="color: #800080">$file_ext</span><span style="color: #000000">);
</span><span style="color: #800080">$file_ext</span> = <span style="color: #008080">strtolower</span>(<span style="color: #800080">$file_ext</span><span style="color: #000000">);
</span><span style="color: #008000">//</span><span style="color: #008000"> 检查扩展名</span>
<span style="color: #0000ff">if</span> (<span style="color: #008080">in_array</span>(<span style="color: #800080">$file_ext</span>,<span style="color: #800080">$ext_arr</span> [<span style="color: #800080">$dir_name</span>]) === <span style="color: #0000ff">false</span><span style="color: #000000">) {
</span><span style="color: #800080">$result</span> = <span style="color: #0000ff">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">);
}
</span><span style="color: #008000">//</span><span style="color: #008000"> 创建<a href="https://www.jb51.cc/tag/wenjian/" target="_blank" class="keywords">文件</a>夹</span>
<span style="color: #0000ff">if</span> (<span style="color: #800080">$dir_name</span> !== ''<span style="color: #000000">) {
</span><span style="color: #0000ff">if</span> (!<span style="color: #008080">file_exists</span>(<span style="color: #800080">$save_url</span><span style="color: #000000">)) {
</span><span style="color: #008080">mkdir</span>(<span style="color: #800080">$save_url</span><span style="color: #000000">);
}
}
</span><span style="color: #800080">$new_file_name</span> = <span style="color: #008080">date</span>('YmdHis') . '_' . <span style="color: #008080">rand</span>(10000,99999) . '.' . <span style="color: #800080">$file_ext</span><span style="color: #000000">;
</span><span style="color: #800080">$file_path</span> = <span style="color: #800080">$save_url</span> . <span style="color: #800080">$new_file_name</span><span style="color: #000000">;
</span><span style="color: #0000ff">if</span> (<span style="color: #008080">move_uploaded_file</span>(<span style="color: #800080">$tmp_name</span>,<span style="color: #800080">$file_path</span>) === <span style="color: #0000ff">false</span><span style="color: #000000">) {
</span><span style="color: #800080">$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">;
</span><span style="color: #800080">$result</span> = <span style="color: #0000ff">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">);
} </span><span style="color: #0000ff">else</span><span style="color: #000000"> {
</span><span style="color: #800080">$result</span> = <span style="color: #0000ff">array</span>('status' => '1','error' => '000000','data' => <span style="color: #800080">$file_path</span><span style="color: #000000">);
}
@</span><span style="color: #008080">chmod</span>(<span style="color: #800080">$file_path</span>,0644<span style="color: #000000">);
</span><span style="color: #0000ff">return</span> <span style="color: #800080">$result</span><span style="color: #000000">;
}
}
</span><span style="color: #0000ff">public</span> <span style="color: #0000ff">function</span> uploadAvatar(<span style="color: #800080">$code</span>,<span style="color: #800080">$avatarImageName</span><span style="color: #000000">) {
</span><span style="color: #800080">$url</span> = <span style="color: #800080">$this</span>->getApiUrl(<span style="color: #ff00ff">__METHOD__</span><span style="color: #000000">);
</span><span style="color: #800080">$data</span> = <span style="color: #0000ff">array</span><span style="color: #000000">(
</span>"code" => <span style="color: #800080">$code</span>,"ip" => <span style="color: #800080">$this</span>->params['ip'],"avatar" => !<span style="color: #0000ff">empty</span>(<span style="color: #800080">$avatarImageName</span>) ? '@' . <span style="color: #800080">$avatarImageName</span> : '',<span style="color: #000000">
);
</span><span style="color: #800080">$result</span> = <span style="color: #800080">$this</span>->curlPost(<span style="color: #800080">$url</span>,<span style="color: #800080">$data</span><span style="color: #000000">);
</span><span style="color: #0000ff">return</span> <span style="color: #800080">$result</span><span style="color: #000000">;
}
}
这样,PHP就已经接收到了来自客户端的 图片上传了,并且已经上传到java后端服务器。
注意:这里有个坑,即PHP版本大于5.6以后,直接使用 @ 符号无法上传文件了,需要 加上一个安全选项:CURLOPT_SAFE_UPLOAD => false 才可以,或者使用5.6以的高级上传类上传文件:
<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">)
</span><span style="color: #0000ff">private</span><span style="color: #000000"> UserService userService;
@RequestMapping(value </span>= "/uploadAvatar",method = RequestMethod.POST,produces = "application/json"<span style="color: #000000">)
@ResponseBody
</span><span style="color: #0000ff">public</span><span style="color: #000000"> 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">throws</span><span style="color: #000000"> MicroException {
bean.setAddIp(addIp);
bean.setUserId(userId);
</span><span style="color: #0000ff">try</span><span style="color: #000000"> {
</span><span style="color: #008000">//</span><span style="color: #008000"> 转型为MultipartHttpRequest:</span>
MultipartHttpServletRequest multipartRequest =<span style="color: #000000"> (MultipartHttpServletRequest) request;
</span><span style="color: #008000">//</span><span style="color: #008000"> 从其中取出一个<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">null</span><span style="color: #000000">;
</span><span style="color: #0000ff">for</span> (Iterator<String> it =<span style="color: #000000"> multipartRequest.getFileNames(); it.hasNext();) {
file </span>=<span style="color: #000000"> multipartRequest.getFile((String) it.next());
}
userService.uploadAvatar(file,bean);
} </span><span style="color: #0000ff">catch</span><span style="color: #000000"> (Exception e) {
</span><span style="color: #0000ff">throw</span> <span style="color: #0000ff">new</span><span style="color: #000000"> 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">new</span><span style="color: #000000"> ResponseEntity(Constants.System.OK);
</span><span style="color: #0000ff">return</span><span style="color: #000000"> ret;
}
}
至此,上传流程已经完成了。(当然,后续还可能使用其他上传,比如dubbo调用文件系统上传文件,调用第三方sdk上传到文件服务器。。。, 原理大抵一样,使用字节流进行传输,然后读取出来存储到文件)
一般为app写的接口中,都会涉及到加解密问题,此时,文件不应该算作加密的范畴,而应单独给一个字段。
原文链接:https://www.f2er.com/php/74357.html