SSM框架实现图片上传
前端代码
<form action="village/${msg }.do" name="Form" id="Form"
method="post" enctype="multipart/form-data">
<input type="hidden" name="id" id="id" value="${pd.id }" /> <input
type="hidden" name="apartment_id" id="apartment_id"
value="${pd.apartment_id }" />
<div id="zhongxin" style="padding-top: 13px;">
<table id="table_report"
class="table table-striped table-bordered table-hover">
<tr>
<td style="width:79px;text-align: right;padding-top: 13px;">小区名:</td>
<td><input type="text" name="apartment_name"
id="apartment_name" value="${pd.apartment_name }"
maxlength="32" style="width:98%;" />
</td>
</tr>
<tr>
<td style="width:79px;text-align: right;padding-top: 13px;">所属地区:</td>
<td><input type="text" name="region" id="region"
value="${pd.region }" maxlength="32" style="width:98%;" />
</td>
</tr>
<tr>
<td style="width:79px;text-align: right;padding-top: 13px;">小区地址:</td>
<td><input type="text" name="village_address"
id="village_address" value="${pd.village_address }"
maxlength="32" style="width:98%;" />
</td>
</tr>
<tr>
<td style="width:79px;text-align: right;padding-top: 13px;">小区介绍:</td>
<td><input type="text" name="v_describe" id="describe"
value="${pd.v_describe }" maxlength="32" style="width:98%;" />
</td>
</tr>
<tr>
<td style="width:110px;text-align: right;padding-top: 13px;">公寓图片:</td>
<td><input type="file" name="img_id" id="img_id"
onchange="fileType(this)" style="width:98%;" /> <input
type="hidden" name="imgname" id="imgname"
value="${pd.img_id}" /></td>
</tr>
<tr>
<td style="text-align: center;" colspan="10"><a
class="btn btn-mini btn-primary" onclick="save();">保存</a> <a
class="btn btn-mini btn-danger"
onclick="top.Dialog.close();">取消</a>
</td>
</tr>
</table>
</div>
<div id="zhongxin2" class="center" style="display:none">
<br /> <br /> <br /> <br /> <img
src="static/images/jiazai.gif" /><br />
<h4 class="lighter block green"></h4>
</div>
</form>
//上传格式
function fileType(obj){
var fileType=obj.value.substr(obj.value.lastIndexOf(".")).toLowerCase();//获得文件后缀名
if(fileType != '.gif' && fileType != '.png' && fileType != '.jpg' && fileType != '.jpeg'){
$("#goods_img").tips({
side:3,
msg:'请上传图片格式的文件',
bg:'#AE81FF',
time:3
});
$("#goods_img").val('');
document.getElementById("goods_img").files[0] = '请选择图片';
}
}
后台代码
/**
* 修改新增图片上传
* @param request
* @param file
* @param id
* @param imgname
* @param apartment_name
* @param region
* @param village_address
* @param v_describe
* @return
* @throws Exception
*/
@RequestMapping(value="editV")
public ModelAndView editv(HttpServletRequest request,
@RequestParam(value="img_id",required=false) MultipartFile file,
@RequestParam(value="id",required=false) Integer id,
@RequestParam(value="apartment_id",required=false) String apartment_id,
@RequestParam(value="imgname",required=false) String imgname,
@RequestParam(value="apartment_name",required=false) String apartment_name,
@RequestParam(value="region",required=false) String region,
@RequestParam(value="village_address",required=false) String village_address,
@RequestParam(value="v_describe",required=false) String v_describe
) throws Exception{
ModelAndView mv=this.getModelAndView();
PageData pd=new PageData();
pd=this.getPageData();
pd.put("id", id);
pd.put("apartment_name", apartment_name);
pd.put("region", region);
pd.put("village_address", village_address);
pd.put("v_describe", v_describe);
if(null == imgname){imgname = "";}
String fileName = "";
if(file!=null && !file.isEmpty()){
String filePath = PathUtil.getWebAppRootPath()+"village_img/" ;
System.out.println(filePath);
fileName = FileUpload.fileUp(file, filePath, this.get32UUID());
System.out.println(filePath);
System.out.println(fileName);
pd.put("img_id", "village_img/" + fileName);
}else{
pd.put("img_id", imgname);
}
if(id!=null){
pd.put("apartment_id", apartment_id);
villageService.edit(pd);
villageImgService.goAddImg(pd);
}else{
pd.put("apartment_id", UuidUtil.get32UUID());
villageService.goAddV(pd);
villageImgService.goAddImg(pd);
}
mv.addObject("msg","success");
mv.setViewName("save_result");
return mv;
}
工具类
public class PathUtil {
/**
* 图片访问路径
* @param pathType
* 图片类型 visit-访问;save-保存
* @param pathCategory
* 图片类别,如:话题图片-topic、话题回复图片-reply、商家图片
* @return
*/
public static String getPicturePath(String pathType, String pathCategory) {
String strResult = "";
// HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
StringBuffer strBuf = new StringBuffer();
if ("visit".equals(pathType)) {
} else if ("save".equals(pathType)) {
String projectPath = PublicUtil.getPorjectPath().replaceAll("\\\\", "/");
projectPath = splitString(projectPath, "bin/");
strBuf.append(projectPath);
strBuf.append("webapps/ROOT/");
}
strResult = strBuf.toString();
return strResult;
}
private static String splitString(String str, String param) {
String result = str;
if (str.contains(param)) {
int start = str.indexOf(param);
result = str.substring(0, start);
}
return result;
}
/**
* getWebAppRootPath
* 获取 项目根路径
* @return
*/
public static String getWebAppRootPath() {
return ContextLoader.getCurrentWebApplicationContext().getServletContext().getRealPath("/");
}
/***
* 获取 template 模板路径
* @return
*/
public static String getWebAppTemplatePath() {
return getWebAppRootPath() + "template/";
}
public static String getTomcatRootPath() {
return new File(getWebAppRootPath()).getParentFile().getParent() + File.separator;
}
public static String getUploadImagePath() {
return getTomcatRootPath() + Const.FILEPATHIMG ;
}
/**获取classpath1
* @return
*/
public static String getClasspath(){
//原路径代码,为tomcat下的路径apache-tomcat-7.0.72/webapps/Creditpaperless/WEB-INF/classes/../../uploadFiles/uploadImgs/20161110
//String path = (String.valueOf(Thread.currentThread().getContextClassLoader().getResource(""))+"../../").replaceAll("file:/", "").replaceAll("%20", " ").trim();
String path ="E:/edmsfile/".trim();
//String path=
if(path.indexOf(":") != 1){
path = File.separator + path;
}
return path;
}
/**获取classpath2
* @return
*/
public static String getClassResources(){
String path = (String.valueOf(Thread.currentThread().getContextClassLoader().getResource(""))).replaceAll("file:/", "").replaceAll("%20", " ").trim();
if(path.indexOf(":") != 1){
path = File.separator + path;
}
return path;
}
public static String PathAddress() {
String strResult = "";
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder
.getRequestAttributes()).getRequest();
StringBuffer strBuf = new StringBuffer();
strBuf.append(request.getScheme() + "://");
strBuf.append(request.getServerName() + ":");
strBuf.append(request.getServerPort() + "");
strBuf.append(request.getContextPath() + "/");
strResult = strBuf.toString();// +"ss/";//加入项目的名称
return strResult;
}
}
public class FileUpload {
/**上传文件
* @param file //文件对象
* @param filePath //上传路径
* @param fileName //文件名
* @return 文件名
*/
public static String fileUp(MultipartFile file, String filePath, String fileName) {
String extName = ""; // 扩展名格式:
try {
if (file.getOriginalFilename().lastIndexOf(".") >= 0) {
extName = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
}
copyFile(file.getInputStream(), filePath, fileName + extName).replaceAll("-", "");
} catch (IOException e) {
System.out.println(e);
}
return fileName + extName;
}
/**
* 写文件到当前目录的upload目录中
* @param in
* @param fileName
* @throws IOException
*/
private static String copyFile(InputStream in, String dir, String realName)
throws IOException {
File file = mkdirsmy(dir,realName);
FileUtils.copyInputStreamToFile(in, file);
return realName;
}
/**判断路径是否存在,否:创建此路径
* @param dir 文件路径
* @param realName 文件名
* @throws IOException
*/
public static File mkdirsmy(String dir, String realName) throws IOException{
File file = new File(dir, realName);
if (!file.exists()) {
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
file.createNewFile();
}
return file;
}
/**下载网络图片上传到服务器上
* @param httpUrl 图片网络地址
* @param filePath 图片保存路径
* @param myFileName 图片文件名(null时用网络图片原名)
* @return 返回图片名称
*/
public static String getHtmlPicture(String httpUrl, String filePath , String myFileName) {
URL url; //定义URL对象url
BufferedInputStream in; //定义输入字节缓冲流对象in
FileOutputStream file; //定义文件输出流对象file
try {
String fileName = null == myFileName?httpUrl.substring(httpUrl.lastIndexOf("/")).replace("/", ""):myFileName; //图片文件名(null时用网络图片原名)
url = new URL(httpUrl); //初始化url对象
in = new BufferedInputStream(url.openStream()); //初始化in对象,也就是获得url字节流
//file = new FileOutputStream(new File(filePath +"\\"+ fileName));
file = new FileOutputStream(mkdirsmy(filePath,fileName));
int t;
while ((t = in.read()) != -1) {
file.write(t);
}
file.close();
in.close();
return fileName;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}