hbuilder 上传1/multifile

前端

<!DOCTYPE html>
<html>

	<head>
		<meta charset="UTF-8">
		<meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
		<title>智慧付油</title>
		<script src="js/jquery.min.js"></script>
		<script src="js/mui.min.js"></script>
		<script src="js/jquery-2.1.1.js"></script>
		<script src="js/server.js"></script>
		<script src="js/app.js"></script>
		<link href="css/mui.min.css" rel="stylesheet" />
		<link href="css/main.css" rel="stylesheet" />
		<link href="fonts/iconfont.css" rel="stylesheet" />
		<style>
			#imageup {
				width: 100px;
				height: 36px;
				line-height: 36px;
			}
			
			#button {
				width: 100px;
				height: 50px;
				line-height: 50px;
			}
		</style>
	</head>
	<script>
		mui.init();

		var name = localStorage.getItem("name");
		var loginname = localStorage.getItem("loginname");
		var office = localStorage.getItem("office");
		var company = localStorage.getItem("company");
		var info = company + '-' + office;

		$(function() {
			if(name != null && name != '' && name != 'undefined') {
				$('#username2').html(name);
				$('#company').text(info);
			}
			var scrname = document.getElementById("headimg");
			var param = {
				"loginname": loginname
			};
			fun_server.actionAjax("/photoView", param, success_fun, error_fun);

			function success_fun(data) {
				scrname.src = data.photo;

			}

			function error_fun(xhr, type, errorThrown) {
				mui.alert(JSON.stringify(xhr) + type + "---" + errorThrown);
			}

		});
		mui.plusReady(function() {
			mui("body").on("tap", "#imageup", function() {
				page.imgUp();
			})
		})
		var page = null;
		page = {
			imgUp: function() {
				var m = this;
				plus.nativeUI.actionSheet({
					cancel: "取消",
					buttons: [{
							title: "拍照"
						},
						{
							title: "从相册中选择"
						}
					]
				}, function(e) { //1 是拍照  2 从相册中选择  
					switch(e.index) {
						case 1:
							appendByCamera(document.getElementById("headimg"));
							break;
						case 2:
							appendByGallery(document.getElementById("headimg"));
							break;
					}
				});
			}
		}
		/*
		            function appendByCamera(){
		                plus.camera.getCamera().captureImage(function(e){
		                    console.log(e);
		                    plus.io.resolveLocalFileSystemURL(e, function(entry) { 
		                    var path = entry.toLocalURL(); 
		                    document.getElementById("headimg").src = path; 
		                    //就是这里www.bcty365.com 
		                    }, function(e) { 
		                        mui.toast("读取拍照文件错误:" + e.message); 
		                    }); 
		    
		                });    
		            }
		            // 从相册添加文件
		            function appendByGallery(){
		                plus.gallery.pick(function(path){
		                
		                    document.getElementById("headimg").src = path; 
		                });
		            }*/

		var url = server_address + "/upload";
		function upfiles() {
			upload(document.getElementById("headimg"), url);
		}

		/* 
            function upload(){
 					var files=document.getElementById("headimg") ;
				//var wt=plus.nativeUI.showWaiting();
                var task = plus.uploader.createUpload("http://192.168.6.64:80/xsgs_znyk/app/upload",
                
						{method: "POST"},
                    function(t,status){ //上传完成
                        if(status==200){
                            mui.alert("图片上传成功");
                           // wt.close(); //关闭等待提示按钮
                        }else{
                            mui.alert("上传失败:"+status+"请联系管理员");
                      //      wt.close();//关闭等待提示按钮
                        }
                    }
                );
                //添加其他参数
                task.addData("name",localStorage.getItem("loginname"));
                task.addFile(files.src,{key:"dddd"});
                task.start();
            }  
           */
	</script>

	<body class="mui-fullscreen">
		<div id="app" class="mui-views" data-view="1">
			<div class="mui-view">
				<div class="mui-navbar">
					<div class="mui-navbar-inner mui-bar mui-bar-nav mui-navbar-center">
						<button type="button" class="mui-left mui-action-back mui-btn  mui-btn-link mui-btn-nav mui-pull-left">
					<span class="mui-icon mui-icon-left-nav"></span>
				</button>
						<h1 class="mui-center mui-title">个人中心</h1>
					</div>
				</div>
				<div class="mui-pages">
					<div id="setting" class="mui-page mui-page-center">
						<!--页面标题栏开始-->

						<!--页面标题栏结束-->
						<!--页面主内容区开始-->
						<div class="mui-page-content admin">
							<div class="mui-scroll-wrapper" data-scroll="2">
								<div class="mui-scroll" style="transform: translate3d(0px, 0px, 0px) translateZ(0px);">
									<ul class="mui-table-view mui-table-view-chevron">
										<li class="mui-table-view-cell mui-media">

											<!--									<img class="mui-media-object mui-pull-left head-img" id="head-img" src="images/user.jpg">
-->
											<div class="mui-media-body" id="username2">
											</div>
											<div>

											</div>
											<p class="mui-media-body" id="company"></p>

										</li>
									</ul>
									<ul class="mui-table-view">

										<li class="mui-table-view-cell">
											<a class="mui-navigate-right"><span class="mui-icon iconfont icon-kujialeqiyezhan_yewupeixun"></span>安全培训</a>
										</li>
									</ul>

									<ul class="mui-table-view">
										<li class="mui-table-view-cell">
											<a class="mui-navigate-right" href="sys/updatePass.html"><span class="mui-icon iconfont icon-shezhi"></span>修改密码</a>
										</li>
										<li class="mui-table-view-cell">
											<a href="sys/info.html" class="mui-navigate-right"><span class="mui-icon iconfont icon-guanyu"></span>关 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;于<i class="mui-pull-right update"></i></a>
										</li>
									</ul>

									<ul class="list" style="align-content: center; align-self: center;">

										<img id="headimg" src="sss" style="text-align: center;" height="150" width="150" align="center">
										<p>
											<a href="javascript:;" id="imageup">上传图片</a>
										</p>
										<p>
											<button onclick="upfiles();" id='button'> 提交</button>
										</p>
									</ul>

									<ul class="mui-table-view">
										<li class="mui-table-view-cell" style="text-align: center;">
											<a id="loginout" onclick="signOutBtn()">退出登录</a>
										</li>
									</ul>
								</div>
								<div class="mui-scrollbar mui-scrollbar-vertical">
									<div class="mui-scrollbar-indicator" style="transition-duration: 0ms; display: none; height: 518px; transform: translate3d(0px, 0px, 0px) translateZ(0px);"></div>
								</div>
							</div>
						</div>
						<!--页面主内容区结束-->
					</div>
				</div>
			</div>
		</div>
		1111
	</body>

	<script>
		function signOutBtn() {
			var btnArray = ['是', '否'];
			mui.confirm('确认要退出登录吗?', '系统提示', btnArray, function(e) {
				if(e.index == 0) {
					localStorage.removeItem("password")
					plus.webview.open('login.html');
					/*mui.openWindow({
								url: 'login.html'
								
							});
						*/
				}
			})
		}
	</script>

</html>

后台

/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package cn.sn.exInterface.modules.app;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.Base64Utils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import cn.sn.dadao.common.config.Global;
import cn.sn.dadao.modules.sys.entity.User;
import cn.sn.dadao.modules.sys.service.SystemService;
import cn.sn.dadao.modules.sys.utils.UserUtils;

/**
 * 终端菜单Controller
 * 
 * @author gdc
 * @version 2018-09-27
 */
@Controller
public class AppUpLoadController {
	@Autowired
	private SystemService systemService;

	@ResponseBody
	@RequestMapping(value = "${frontPath}/upload")
	public void meanView(HttpServletRequest request, HttpServletResponse response,
			@RequestParam("dddd") MultipartFile file) {
		String path = Global.getProjectPath() + "/userfiles/1/images/photo/" + file.getOriginalFilename();
		String realpath = path.substring(path.indexOf("/userfiles/1/images/photo/" + file.getOriginalFilename()));

		File targetFile = new File(path);

		try {
			file.transferTo(targetFile);
			String loginname = request.getParameter("name");
			User user = UserUtils.getByLoginName(loginname);
			user.setPhoto(realpath);
			systemService.saveUser(user);
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	@ResponseBody
	@RequestMapping(value = "${frontPath}/photoView")
	public Map<String, Object> photoView(HttpServletRequest request, HttpServletResponse response) {
		String loginname = request.getParameter("loginname");
		String path = "";
		try {
			User user = UserUtils.getByLoginName(loginname);
			path = user.getPhoto();
		} catch (Exception e) {
			e.getStackTrace();
		}
		String severaddress = "http://" + request.getServerName() + ":" + request.getServerPort()
				+ request.getContextPath();
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("photo", severaddress + path);
		return map;
	}

	@ResponseBody
	@RequestMapping(value = "${frontPath}/uploadTest")
	public Map<String, Object> uploadTest(HttpServletRequest request, HttpServletResponse response) {
		String name = request.getContextPath();
		Map<String, Object> map = new HashMap<String, Object>();
		String base64Data = request.getParameter("imageBase64");
		String dataPrix = "";
		String data = "";
		try {
			if (base64Data == null || "".equals(base64Data)) {
				throw new Exception("上传失败,上传图片数据为空");
			} else {
				String[] d = base64Data.split("base64,");
				System.out.println(d.length);
				if (d != null && d.length == 2) {
					dataPrix = d[0];
					data = d[1];
				} else {
					throw new Exception("上传失败,数据不合法");
				}
			}
			String suffix = "";
			if ("data:image/jpeg;".equalsIgnoreCase(dataPrix)) {
				suffix = ".jpg";
			} else if ("data:image/x-icon;".equalsIgnoreCase(dataPrix)) {
				suffix = ".ico";
			} else if ("data:image/gif;".equalsIgnoreCase(dataPrix)) {
				suffix = ".gif";
			} else if ("data:image/png;".equalsIgnoreCase(dataPrix)) {
				suffix = ".png";
			} else {
				throw new Exception("上传图片格式不合法");
			}
			String tempFileName = UUID.randomUUID().toString() + suffix;
			byte[] bs = Base64Utils.decodeFromString(data);
			try {
				FileUtils.writeByteArrayToFile(
						new File(Global.getProjectPath() + "/userfiles/1/images/photo/", tempFileName), bs);
				map.put("url", "http://" + request.getServerName() + ":" + request.getServerPort() + name
						+ "/userfiles/1/images/photo/" + tempFileName);
				map.put("result", "上传成功");
			} catch (Exception ee) {
				throw new Exception("上传失败,写入文件失败," + ee.getMessage());
			}
		} catch (Exception e) {
			// TODO: handle exception
			map.put("result", "图片上传失败,请稍后再试");
		}
		return map;

	}

}

猜你喜欢

转载自blog.csdn.net/gaoduicai/article/details/82943004