1、前端html

<div class="form-group">
    <label for="inputPassword3" class="col-sm-2 control-label">身份证正面照片:</label>
    <div class="col-sm-10">
    <input type="hidden" name="img" id="photoUrl"/>
    <input type="file" name="logoFile" id="logoFile" onchange="setImg(this);">
    <span><img id="photourlShow" src="" width="300" height="197"/></span>
    </div>
</div>

2、js

//用于进行图片上传,返回地址
function setImg(obj){
var f=$(obj).val();
alert(f);
console.log(obj);
if(f == null || f ==undefined || f == ''){
return false;
}
if(!/\.(?:png|jpg|bmp|gif|PNG|JPG|BMP|GIF)$/.test(f))
{
alert("类型必须是图片(.png|jpg|bmp|gif|PNG|JPG|BMP|GIF)");
$(obj).val('');
return false;
}
var data = new FormData();
console.log(data);
$.each($(obj)[0].files,function(i,file){
data.append('file', file);
});
console.log(data);
$.ajax({
type: "POST",
url: GLOBAL_INFO.WEBURL_PREFIX+"business/uploadImg.xhtml",
data: data,
cache: false,
contentType: false, //不可缺
processData: false, //不可缺
dataType:"json",
success: function(ret) {
console.log(ret);
if(ret.code==0){
$("#photoUrl").val(ret.result.url);//将地址存储好
$("#photourlShow").attr("src",ret.result.url);//显示图片
alertOk(ret.message);
}else{
alertError(ret.message);
$("#url").val("");
$(obj).val('');
}
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("上传失败,请检查网络后重试");
}
});
}

3、后台代码

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Random; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import org.springframework.stereotype.Controller;
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 com.alibaba.fastjson.JSON;
import com.siyang.CommonUtil.BaseController;
import com.siyang.entity.ResponseResult;
/**
* 照片上传工具类
* @author admin
*
*/
@Controller
@RequestMapping("/business")
public class UploaderController extends BaseController{
@ResponseBody
@RequestMapping("/uploadImg.xhtml")
public void uploadPicture(@RequestParam(value="file",required=false)MultipartFile file,HttpServletRequest request,HttpServletResponse response){
ResponseResult result = new ResponseResult();
Map<String, Object> map = new HashMap<String, Object>();
File targetFile=null;
String url="";//返回存储路径
int code=1;
System.out.println(file);
String fileName=file.getOriginalFilename();//获取文件名加后缀
if(fileName!=null&&fileName!=""){
String returnUrl = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath() +"/upload/imgs/";//存储路径
String path = request.getSession().getServletContext().getRealPath("upload/imgs"); //文件存储位置
String fileF = fileName.substring(fileName.lastIndexOf("."), fileName.length());//文件后缀
fileName=new Date().getTime()+"_"+new Random().nextInt(1000)+fileF;//新的文件名 //先判断文件是否存在
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
String fileAdd = sdf.format(new Date());
//获取文件夹路径
File file1 =new File(path+"/"+fileAdd);
//如果文件夹不存在则创建
if(!file1 .exists() && !file1 .isDirectory()){
file1 .mkdir();
}
//将图片存入文件夹
targetFile = new File(file1, fileName);
try {
//将上传的文件写到服务器上指定的文件。
file.transferTo(targetFile);
url=returnUrl+fileAdd+"/"+fileName;
code=0;
result.setCode(code);
result.setMessage("图片上传成功");
map.put("url", url);
result.setResult(map);
} catch (Exception e) {
e.printStackTrace();
result.setMessage("系统异常,图片上传失败");
}
}
writeJson(response, result);
}
}

4、结果集实体类

package com.siyang.entity;

import java.util.Map;

public class ResponseResult {
private Integer code; private String message; private Map<String, Object> result; public Integer getCode() {
return this.code;
} public void setCode(Integer code) {
this.code = code;
} public String getMessage() {
return this.message;
} public void setMessage(String message) {
this.message = message;
} public Map<String, Object> getResult() {
return this.result;
} public void setResult(Map<String, Object> result) {
this.result = result;
} }

5、向页面返回结果

package com.siyang.CommonUtil;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter; import javax.servlet.http.HttpServletResponse; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import com.google.gson.Gson; public class BaseController {
protected Logger logger = LoggerFactory.getLogger(getClass());
/**
* 输出JSON数据
*
* @param response
* @param jsonStr
*/
public void writeJson(HttpServletResponse response, String jsonStr) {
response.setContentType("text/json;charset=utf-8");
response.setHeader("Pragma", "No-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
PrintWriter pw = null;
try {
pw = response.getWriter();
pw.write(jsonStr);
pw.flush();
} catch (Exception e) {
logger.info("输出JSON数据异常", e);
}finally{
if(pw!=null){
pw.close();
}
}
}
/**
*
* 向页面响应json字符数组串流.
*
* @param response
* @param jsonStr
* @throws IOException
* @return void
* @author 蒋勇
* @date 2015-1-14 下午4:18:33
*/
public void writeJsonStr(HttpServletResponse response, String jsonStr) throws IOException { OutputStream outStream = null;
try {
response.reset();
response.setCharacterEncoding("UTF-8");
outStream = response.getOutputStream();
outStream.write(jsonStr.getBytes("UTF-8"));
outStream.flush();
} catch (IOException e) {
logger.info("输出JSON数据异常(writeJsonStr)", e);
} finally {
if(outStream!=null){
outStream.close();
}
}
} public void writeJsonStr(HttpServletResponse response, InputStream in) throws IOException { if(null == in ){
return ;
}
OutputStream outStream = null;
try {
response.reset();
response.setCharacterEncoding("UTF-8");
response.setHeader("Pragma", "No-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
outStream = response.getOutputStream();
int len = 0;
byte[] byt = new byte[1024];
while ((len = in.read(byt)) != -1) {
outStream.write(byt, 0, len);
}
outStream.flush(); } catch (IOException e) { logger.info("输出JSON数据异常(writeJsonStr)", e);
} finally {
if(outStream!=null){
outStream.close();
in.close();
}
}
} /**
* 输出JSON数据
*
* @param response
* @param jsonStr
*/
public void writeJson(HttpServletResponse response, Object obj) {
response.setContentType("text/json;charset=utf-8");
response.setHeader("Pragma", "No-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
PrintWriter pw = null;
Gson gson = new Gson();
try {
pw = response.getWriter();
pw.write(gson.toJson(obj)); pw.flush();
} catch (Exception e) {
logger.info("输出JSON数据异常", e);
}finally{
if(pw!=null){
pw.close();
}
}
} public void writeHtml(HttpServletResponse response, String html) {
response.setContentType("text/html;;charset=utf-8");
response.setHeader("Pragma", "No-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
PrintWriter pw = null;
try {
pw = response.getWriter();
pw.write(html);
pw.flush();
} catch (Exception e) {
logger.info("输出HTML数据异常", e);
}finally{
if(pw!=null){
pw.close();
}
}
}
}

摘自:https://blog.csdn.net/weixin_40050532/article/details/80799708

java实现图片上传功能,并返回图片保存路径的更多相关文章

  1. Spring+SpringMVC+MyBatis+easyUI整合优化篇(七)图片上传功能

    日常啰嗦 前一篇文章<Spring+SpringMVC+MyBatis+easyUI整合优化篇(六)easyUI与富文本编辑器UEditor整合>讲了富文本编辑器UEditor的整合与使用 ...

  2. PHP语言学习之php做图片上传功能

    本文主要向大家介绍了PHP语言学习之php做图片上传功能,通过具体的内容向大家展示,希望对大家学习php语言有所帮助. 今天来做一个图片上传功能的插件,首先做一个html文件:text.php < ...

  3. H5 利用vue实现图片上传功能。

    H5的上传图片如何实现呢? 以下是我用vue实现的图片上传功能,仅供参考. <!DOCTYPE html> <html> <head> <meta chars ...

  4. vue 图片上传功能

    这次做了vue页面的图片上传功能,不带裁剪功能的! 首先是html代码,在input框上添加change事件,如下:   <ul class="clearfix">   ...

  5. 前端丨如何使用 tcb-js-sdk 实现图片上传功能

    前言 tcb-js-sdk 让开发者可以在网页端使用 JavaScript 代码服务访问云开发的服务,以轻松构建自己的公众号页面或者独立的网站等 Web 服务.本文将以实现图片上传功能为例,介绍 tc ...

  6. 从web编辑器 UEditor 中单独提取图片上传,包含多图片单图片上传以及在线涂鸦功能

    UEditor是由百度web前端研发部开发所见即所得富文本web编辑器,具有轻量,可定制,注重用户体验等特点,开源基于MIT协议,允许自由使用和修改代码.(抄的...) UEditor是非常好用的富文 ...

  7. thinkphp达到UploadFile.class.php图片上传功能

    片上传在站点里是非经常常使用的功能.ThinkPHP里也有自带的图片上传类(UploadFile.class.php) 和图片模型类(Image.class.php).方便于我们去实现图片上传功能,以 ...

  8. [Ting's笔记Day8]活用套件carrierwave gem:(3)Deploy图片上传功能到Heroku网站

    前情提要: 身为Ruby新手村民,创造稳定且持续的学习步调很重要,我用的方法就是一周在IT邦写三篇笔记,希望藉由把笔记和遇到的bug记录下来的过程,能帮助到未来想用Ruby on Rails架站的新手 ...

  9. asp.net core 如何集成kindeditor并实现图片上传功能

     准备工作 1.visual studio 2015 update3开发环境 2.net core 1.0.1 及以上版本  目录 新建asp.net core web项目 下载kindeditor ...

  10. 给DEDECMS广告管理中增加图片上传功能

    dedecms的广告管理功能稍微有点次,本文就是在dedecms广告管理原有的基础上增加广告图片上传功能. 安装方法,对应自己的dedecms版本下载对应的编码然后解压把里面的文件放在后台目录覆盖即可 ...

随机推荐

  1. 生成PDF文档之iText

    iTextSharp.text.Document:这是iText库中最常用的类,它代表了一个pdf实例.如果你需要从零开始生成一个PDF文件,你需要使用这个Document类.首先创建(new)该实例 ...

  2. 异步socket处理

    服务器端: #include <boost/thread.hpp> #include <boost/asio.hpp> #include <boost/date_time ...

  3. 在Ubuntu 12.04 上为Virtualbox 启用USB 设备支持

    在Ubuntu 12.04 上为Virtualbox 启用USB 设备支持  http://www.cnblogs.com/ericsun/archive/2013/06/10/3130679.htm ...

  4. learning ddr mode reigster set command cycle time tMRD and tMOD

    tMRD: tMOD:

  5. day_07_python_1124

    01 昨日内容回顾 数据类型补充: str <---> list split join list <---> set set(list) list(set()) list &l ...

  6. 公司最近把开发人员的系统全部改为windows了

    公司最近把开发人员的开发环境全部改为windows了,唯一linux系统(一位做python 开发的同事自己安装的),被要求下午下班前改为windows 系统,windows 是公认的不适合开发,我家 ...

  7. MariaDB的线程及连接

    转自 linux公社 今天在这里介绍一下确认mariaDB(和MySQL一样)的链接数及线程数的方法.MariaDB和MySQL有什么不一样,现在还没有弄清楚. 这是减少数据库的负载,并能提高数据库运 ...

  8. 每天CSS学习之text-align

    text-align是CSS的一个属性,其作用是设置文本的对齐方式.其值如下所示: 1.left:文本左对齐.如下所示: div{ text-align:left; } 结果: 2.right:文本右 ...

  9. Vue基础以及指令

    Vue 基础篇一   一.Vue框架介绍 之前大家学过HTML,CSS,JS,JQuery,Bootstrap,现在我们要学一个新的框架Vue~ Vue是一个构建数据驱动的web界面的渐进式框架. 目 ...

  10. 怎样关掉 ubuntu 中的 System Program Problem Detected 提示框

    怎样关掉 ubuntu 中的 System Program Problem Detected 提示框 方法如下:sudo gedit /etc/default/apport  打开该文件如下:# se ...