转载自:https://blog.csdn.net/wyg1995/article/details/79772555
今天在做mui手机APP上传照片,网上看了很多教程不太详细,这一篇我觉得代码挺不错了,转载一下。
<html>
<button onclick="openCamera()">tapmeToPhoto</button>
</html>
<script>
var config = {
//api: "http://192.168.2.195/",
api: "http://192.168.2.217/",
//maxupload: 2 * 1024 * 1024,
};
function openCamera() {
var cmr = plus.camera.getCamera();
cmr.captureImage(function(p) {
plus.io.resolveLocalFileSystemURL(p, function(entry) {
// plus.nativeUI.showWaiting("人脸识别中", ""); //显示系统loading框
plus.zip.compressImage({
src: entry.toLocalURL(),
dst: '_doc/camera/' + p,
overwrite: true,
format: "jpg",
width: "30%"
}, function(zip) {
if(zip.size > (1 * 1024 * 1024)) {
return mui.toast('文件超大,请调整相机重新拍照');
}
file_url = zip.target;
//alert(file_url); //此处可以打印是否成功获取拍照所得到的照片
var task = plus.uploader.createUpload(
config.api + "/attach/upload", { // 后端上传接口
method: "POST",
blocksize: 20 * 1024,
priority: 100
},
function(r, status) {
alert(JSON.stringify(r))
plus.nativeUI.closeWaiting();
onresult(JSON.parse(r.responseText))
});
task.setRequestHeader("X-Request-Platform", "app")
if(null != localStorage.getItem("token")) {
task.setRequestHeader("X-Request-Token", localStorage.getItem("token"))
}
if(typeof file_url.files == "object") { // 此处 添加 upload请求的参数
var files = file_url.files;
for(var i in files) {
task.addFile(files[i], {
key: files[i]
})
}
} else {
task.addFile(file_url, {
key: file_url
})
}
task.start();
}, function(zipe) {
plus.nativeUI.closeWaiting();
mui.toast('压缩失败!')
});
}, function(e) {
plus.nativeUI.closeWaiting(); //获取图片失败,loading框取消
mui.toast('失败:' + e.message); //打印失败原因,或给出错误提示
});
}, function(e) {
plus.nativeUI.closeWaiting(); //开启照相机失败,关闭loading框
mui.toast('失败:' + e.message); //打印错误原因,给出错提示
}, {
filename: '_doc/camera/', //图片名字
index: 1 //摄像头id
});
}
</script>
后端代码:
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import com.alibaba.fastjson.JSON;
@Controller
@RequestMapping(value = "attach", method = RequestMethod.POST)
public class AttachController {
@ResponseBody
@RequestMapping("/upload")
public Object upload(HttpServletRequest request, HttpServletResponse resp, HttpSession session)
throws IOException, Exception {
List<Object> list = new ArrayList<Object>();
if (StringUtils.isNotBlank(request.getParameter("base64data"))) {
Object r = this.uploadtolocal(request.getParameter("base64data"));
list.add(r);
} else {
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
Map<String, MultipartFile> o = multipartRequest.getFileMap();
if (o.size() > 0) {
MultipartFile multipartFile = null;
;
for (String k : o.keySet()) {
multipartFile = o.get(k);
Object r = attachService.upload(multipartFile);
list.add(r);
}
}
}
}
/**
* 上传到本地服务器
*/
public Object uploadtolocal(String base64data) throws IOException, Exception {
String originalFilename ="uploadtolocal.jpg";
String filename = MD5Util.encode(""+System.currentTimeMillis());
String suffix = ".jpg";
String str = attachConfig.getDirstring();
String dir1 = ""+str.charAt((int) (Math.random()*15));
String dir2 = ""+str.charAt((int) (Math.random()*15));
if(originalFilename.endsWith(".jpg") || originalFilename.endsWith(".jpeg")){
suffix = ".jpg";
}else if(originalFilename.endsWith(".png")){
suffix = ".png";
}else if(originalFilename.endsWith(".bmp")){
suffix = ".bmp";
}else if(originalFilename.endsWith(".gif")){
suffix = ".gif";
}else if(originalFilename.endsWith(".mp3")){
suffix = ".mp3";
dir1 = "x";
}else if(originalFilename.endsWith(".mp4")){
suffix = ".mp4";
dir1 = "y";
}else if(originalFilename.endsWith(".rar")){
suffix = ".rar";
dir1 = "z";
}else if(originalFilename.endsWith(".zip")){
suffix = ".zip";
dir1 = "z";
}else if(originalFilename.endsWith(".xls")){
suffix = ".xls";
dir1 = "z";
}else if(originalFilename.endsWith(".doc")){
suffix = ".doc";
dir1 = "z";
}else if(originalFilename.endsWith(".docx")){
suffix = ".docx";
dir1 = "z";
}else if(originalFilename.endsWith(".xlsx")){
suffix = ".xlsx";
dir1 = "z";
}else{
throw new Exception("不支持的文件类型");
}
String level = attachConfig.getLevel().toString();
String key="";
String fileid = "";
if("2".equals(level)){
fileid = "2" + dir1 + dir2 + filename + suffix;
key = dir1 + "/" +dir2 + "/2" + dir1 + dir2 + filename + suffix;
}else{
fileid = "1" + dir1 + filename + suffix;
key = dir1 + "/1" + dir1 + filename + suffix;
}
FileUtil.makeDirectory(attachConfig.getLocalroot() + "/" + key);
File saveFile = new File(attachConfig.getLocalroot() + "/" + key);
Decoder decoder = Base64.getDecoder();
FileOutputStream write = new FileOutputStream(saveFile);
write.write(decoder.decode(base64data));
write.close();
Map<String,Object> map = new HashMap<String,Object>();
map.put("fileid",fileid);
map.put("fileurl","http://"+attachConfig.getLocaldomain()+attachConfig.getLocalctxpath()+"/"+key);
map.put("errcode",0);
map.put("url","http://"+attachConfig.getLocaldomain()+attachConfig.getLocalctxpath()+"/"+key);
map.put("error",0);
map.put("errmsg","你的文件已经上传成功");
return map;
}
}
public class AttachConfig {
private String localdomain;
private String localroot;
private String localctxpath;
private String aliossaccesskeyid;
private String aliossaccesskeysecret;
private String aliossbucket;
private String aliossendpoint;
private String aliossdomain;
private Integer level;
private String dirstring;
private String strategy;
public String getLocaldomain() {
return localdomain;
}
public void setLocaldomain(String localdomain) {
this.localdomain = localdomain;
}
public String getLocalroot() {
return localroot;
}
public void setLocalroot(String localroot) {
this.localroot = localroot;
}
public String getAliossbucket() {
return aliossbucket;
}
public void setAliossbucket(String aliossbucket) {
this.aliossbucket = aliossbucket;
}
public String getAliossendpoint() {
return aliossendpoint;
}
public void setAliossendpoint(String aliossendpoint) {
this.aliossendpoint = aliossendpoint;
}
public String getAliossdomain() {
return aliossdomain;
}
public void setAliossdomain(String aliossdomain) {
this.aliossdomain = aliossdomain;
}
public Integer getLevel() {
return level;
}
public void setLevel(Integer level) {
this.level = level;
}
public String getDirstring() {
return dirstring;
}
public void setDirstring(String dirstring) {
this.dirstring = dirstring;
}
public String getStrategy() {
return strategy;
}
public void setStrategy(String strategy) {
this.strategy = strategy;
}
public String getLocalctxpath() {
return localctxpath;
}
public void setLocalctxpath(String localctxpath) {
this.localctxpath = localctxpath;
}
public String getAliossaccesskeyid() {
return aliossaccesskeyid;
}
public void setAliossaccesskeyid(String aliossaccesskeyid) {
this.aliossaccesskeyid = aliossaccesskeyid;
}
public String getAliossaccesskeysecret() {
return aliossaccesskeysecret;
}
public void setAliossaccesskeysecret(String aliossaccesskeysecret) {
this.aliossaccesskeysecret = aliossaccesskeysecret;
}
}
##attach配置
attach.level=2
attach.dirstring=0123456789abcdef
attach.strategy=alioss
attach.localdomain=192.168.2.195
attach.localroot=E:/alidata/szssvip
attach.localctxpath=/mnt
attach.aliossaccesskeyid=U8IN762NbY0wyg5R
attach.aliossaccesskeysecret=0crYUKVXbhkzmfitP0D09AIBexXhmY
attach.aliossbucket=xldev
attach.aliossendpoint=oss-cn-shenzhen.aliyuncs.com
attach.aliossdomain=xldev.oss-cn-shenzhen.aliyuncs.com