前台:
js:
var app = getApp()
var total = [];
Page({
data: {
},
chooseImg: function () {
var _this = this;
wx.chooseImage({
count: 9, // 默认9
sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有
sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有
success: function (res) {
// 返回选定照片的本地文件路径列表,tempFilePath可以作为img标签的src属性显示图片
var tempFilePaths = res.tempFilePaths;
console.log(res)
_this.setData({
img_l: res.tempFilePaths
})
console.info(res.tempFilePaths.length);
}
})
},
loadimg: function () {
var _this = this;
wx.uploadFile({
url: 'http://127.0.0.1/xiaoyuan/goods/upload.php', //接口
filePath: _this.data.img_l[0],
name: 'file',
formData: {
'user': 'test'
},
success: function (res) {
var data = res.data;
console.log(data);
},
fail: function (error) {
console.log(error);
}
})
}
})
wxml:
<button bindtap="chooseImg" style='width:80%'>请添加商品图片</button>
<image style='width: 400px;height: 400px;border:1px solid #ccc;margin: 5px;' src='{{img_l}}'/>
<button bindtap='loadimg' style='width:80%; background-color: rgb(90, 199, 69);'>上传</button>
后台(php):
upload.php:
<?php
date_default_timezone_set(PRC); //设置时区
$code = $_FILES['file'];//获取小程序传来的图片
$uploaded_file=$_FILES['file']['tmp_name'];
$user_path=$_SERVER['DOCUMENT_ROOT']."/xiaoyuan/"."/goods/"."img"; //放到服务器下指定的文件夹
$move_to_file=$user_path."/".$_FILES['file']['name'];
$file_true_name=$_FILES['file']['name'];
echo $file_true_name;
echo $move_to_file;
move_uploaded_file($uploaded_file,iconv("utf-8","gb2312",$move_to_file));
?>
java:
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;
public class Uploadimage extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req,resp);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8"); //设置编码
DiskFileItemFactory factory = new DiskFileItemFactory();
String str = request.getSession().getServletContext().getRealPath("");
String path = request.getRealPath("/upload");
String pathStr=null;
System.err.println("上传的图片路径:"+path);
factory.setRepository(new File(path));
factory.setSizeThreshold(1024*1024) ;
ServletFileUpload upload = new ServletFileUpload(factory);
try {
//可以上传多个文件
@SuppressWarnings("unchecked")
List<FileItem> list = (List<FileItem>)upload.parseRequest(request);
for(FileItem item : list){
String name = item.getFieldName();
if(item.isFormField()){
}else {
//获取路径名
System.out.println("item.getFieldName()是"+item.getFieldName());
String value = item.getName() ;
System.out.println("item.getName()是"+item.getName());
String filename= value;
System.out.println("filename----->"+filename);
str+="/xiaoyuan/"+"/goods/"+"/img/"+filename;
System.out.println("文件存储的路径:"+str);
pathStr=filename;
File file=new File(str);
OutputStream out = new FileOutputStream(file);
InputStream in = item.getInputStream() ;
int length = 0 ;
byte [] buf = new byte[1024] ;
System.out.println("获取上传文件的总共的容量:"+item.getSize());
while( (length = in.read(buf) ) != -1){
out.write(buf, 0, length);
}
in.close();
out.close();
}
}
} catch (FileUploadException e) {
e.printStackTrace();
}
catch (Exception e) {
}
PrintWriter printWriter=response.getWriter();
// printWriter.print("{"path":""+pathStr+""}");
System.out.println("pathStr----->"+pathStr);
printWriter.write(pathStr);
printWriter.print(pathStr);
printWriter.flush();
printWriter.close();
}
}