开始项目只是需要上传文件, 所以只给了个 input type=file
后来我觉得样式不好看, 所以自定义了样式
2018.3.23 更新, 解决了裁剪 BUG
GIF 需要鼠标放上去才会动 23333
上传文件 优化样式
- <div class="row c-row js-ledger-show" id="divFile">
- <label for="name" class="c-row-item__label c-row-item__label_requiredIsPass"> 选择附件 </label>
- <div class="c-row-item__content">
- <div class="c-row-input a-upload">
- <div class="showFileName"> 请选择附件 </div>
- <input type="file" rows="2" class="c-row-input__inner" name="appendix.documentFile" id="documentFileAddInput" />
- <input type="hidden" name="appendix.documentFileExt" id="documentFileExtAddInput" />
- <input type="hidden" name="appendix.documentFileName" id="documentFileNameAddInput">
- </div>
- <!-- 进度条标签 -->
- <progress value="0" max="100" id="progress" style="height: 20px; width: 100%"></progress>
- <div class="c-row--item__error"></div>
- </div>
- </div>
html 相同 js 不同
- $('.a-upload').on("change","input[type='file']",function(){
- var filePath=$(this).val(); // 获取完整路径
- var arr=filePath.split('\\'); // 切文件名
- var fileName=arr[arr.length-1]; // 获得文件名称
- $(".showFileName").html(fileName); // 把文件名显示出来
- });
上传文件有进度条 根据文件大小来跑进度条
代码其实都差不多 根据自己的需求和样式做了一些修改
- <script type="text/javascript">
- $(function(){
- // 上传文件 优化样式 进度条
- $('.a-upload').on("change","input[type='file']",function (){
- // 获取 file 对象
- var domFile = $(this);
- var domForm = $('#appendixAddForm')[0];
- // 将 form 对象直接作为参数 new FormData 对象
- var formData = new FormData(domForm);
- // 追加 file 对象
- formData.append('file',domFile);
- // 截取名称
- var filePath=$(this).val();
- var arr=filePath.split('\\');
- var fileName=arr[arr.length-1];
- formData.append('fileName',fileName);
- $.ajax({
- url:'appendixAction!eachJsonUploadFile.action?appendix.institution.institutionId='+"${institutionId }",
- type: "POST",
- data: formData,
- processData: false,
- contentType: false,
- xhr: function(){
- var xhr = jQuery.ajaxSettings.xhr();
- xhr.upload.onload = function (){
- $(".showFileName").html("读取成功" + fileName);
- }
- xhr.upload.onprogress = function (ev) {
- console.log(ev);
- if(ev.lengthComputable) {
- var percent = 100 * ev.loaded/ev.total;
- //console.log(percent,ev)
- // 进度条动画
- $(".showFileName").html("正在上传" + fileName);
- $('#progress').val(percent);
- }
- }
- return xhr;
- },
- success:function(data){
- // 连接成功结束
- $(".showFileName").html("上传完成" + fileName);
- }
- })
- })
- });
- </script>
- JAVA
- // 修改头像
- public void eachJsonUpdatePicture() {
- try {
- if(employee.getRole()==null||employee.getRole().getRoleId()==null)
- employee.setRole(null);
- String cropData = request.getParameter("cropData");
- if(cropData == null){
- Employee employeeNew = new Employee();
- employeeNew.setEmployeeId(employee.getEmployeeId());
- employeeNew=employeeService.queryOne(employeeNew);
- employeeNew.setPicture(employee.getPicture());
- employeeService.update(employeeNew);
- }else{
- JSONObject jsonCropData = new JSONObject(cropData);
- String initw = request.getParameter("initw");
- String inith = request.getParameter("inith");
- if(initw!=null&&inith!=null){
- employeeService.updatePicture(employee,jsonCropData.getInt("x"),jsonCropData.getInt("y"),Integer.parseInt(inith),Integer.parseInt(initw));
- }else{
- employeeService.updatePicture(employee,jsonCropData.getInt("x"),jsonCropData.getInt("y"),jsonCropData.getInt("h"),jsonCropData.getInt("w"));
- }
- Employee employeeNew = new Employee();
- employeeNew.setEmployeeId(employee.getEmployeeId());
- employeeNew=employeeService.queryOne(employeeNew);
- this.request.getSession().setAttribute("currentUser", employeeNew);
- }
- JSONObject jsonResponse = new JSONObject();
- jsonResponse.put("result", "success");
- jsonResponse.put("message", "修改'员工'成功!");
- HttpJsonUtil.writeJsonData(response, jsonResponse);
- OperateLog operateLog = new OperateLog();
- operateLog.setOperator((Employee) request.getSession().getAttribute("currentUser"));
- operateLog.setLogType(5);
- operateLog.setHappenTime(new Date());
- operateLog.setLogContent("修改'员工'成功!");
- employeeService.saveOrUpdate(operateLog);
- } catch (CurrentException ce) {
- JSONObject jsonResponse = new JSONObject();
- try {
- jsonResponse.put("result", "failed");
- jsonResponse.put("message", ce.getMessage());
- HttpJsonUtil.writeJsonData(response, jsonResponse);
- } catch (Exception e1) {
- e1.printStackTrace();
- }
- OperateLog operateLog = new OperateLog();
- operateLog.setOperator((Employee) request.getSession().getAttribute("currentUser"));
- operateLog.setLogType(5);
- operateLog.setHappenTime(new Date());
- operateLog.setLogContent("操作'员工'异常,"+ce.getMessage());
- employeeService.saveOrUpdate(operateLog);
- } catch (Exception ex) {
- ex.printStackTrace();
- JSONObject jsonResponse = new JSONObject();
- try {
- jsonResponse.put("result", "failed");
- jsonResponse
- .put("message", "发生异常!");
- HttpJsonUtil.writeJsonData(response, jsonResponse);
- } catch (Exception e1) {
- e1.printStackTrace();
- }
- OperateLog operateLog = new OperateLog();
- operateLog.setOperator((Employee) request.getSession().getAttribute("currentUser"));
- operateLog.setLogType(5);
- operateLog.setHappenTime(new Date());
- operateLog.setLogContent("操作'员工'异常!");
- employeeService.saveOrUpdate(operateLog);
- }
- }
- public void updatePicture(Employee employee,int x,int y,int h,int w) throws Exception {
- employeeDao.queryForUpdate(employee);
- Employee employeeNew = new Employee();
- employeeNew.setEmployeeId(employee.getEmployeeId());
- employeeNew = employeeDao.queryOne(employeeNew);
- employeeNew.setPicture(employee.getPicture());
- if (employee.getPicture() == null||employee.getPicture().isEmpty()) {
- FileUtil.DeleteFile(ServletActionContext.getServletContext().getRealPath("/upload/images/employee/")+"/"+employee.getPictureOld());
- }
- if (employee.getPictureFile() != null) {
- FileUtil.DeleteFile(ServletActionContext.getServletContext().getRealPath("/upload/images/employee/")+"/"+employee.getPicture());
- String filename = "employeePicture_" + employee.getEmployeeId() + ".jpg";//employee.getPictureFileExt();
- InputStream is = new FileInputStream(employee.getPictureFile());
- //FileOutputStream fos = new FileOutputStream(new File);
- File file = new File(ServletActionContext.getServletContext().getRealPath("/upload/images/employee/"),
- filename);
- FileUtil.SaveUploadFile(employee.getPictureFile(), ServletActionContext.getServletContext().getRealPath("/upload/images/employee/"),
- filename);
- ImageUtil.cutImage(employee.getPictureFile(),file,x,y,h,w);
- ByteArrayOutputStream outputStream = null;
- ByteArrayInputStream swapStream = null;
- OutputStream output = null;
- try{
- outputStream = CompressImage.compressImage(file,150, 150, (double)0);
- swapStream = new ByteArrayInputStream(outputStream.toByteArray());
- // 第 2 步: 通过子类实例化父类对象
- output = new FileOutputStream(file);// 通过对象多态性, 进行实例化
- // 第 3 步: 进行写操作
- byte[] buffer = new byte[1024];
- int len = 0;
- while ((len = swapStream.read(buffer)) != -1) {
- output.write(buffer, 0, len);
- output.flush();
- }
- }catch(Exception e){
- e.printStackTrace();
- }finally{
- try{
- if(outputStream!=null){
- outputStream.close();
- outputStream = null;
- }
- }catch(Exception e){
- }
- try{
- if(swapStream!=null){
- swapStream.close();
- swapStream = null;
- }
- }catch(Exception e){
- }
- try{
- if(output!=null){
- output.close();
- output = null;
- }
- }catch(Exception e){
- }
- }
- employeeNew.setPicture(filename);
- }
- }
来源: http://www.qdfuns.com/article/24547/f0f9de9efa17d2d5e95f2232969d47ff.html