Java大牛养成记——图片上传


背景:感觉过了好久没有好好的写文章了,今天休息就来整理一下最近接触到的内容吧。顺便梳理一下学习到的知识。今天需要梳理的内容是图片的上传。


一、前期准备


在配置文件中配置你要上传的路径:

picture_windows=E\:\\picture\\

picture_linux=/home/picture/


二、JSP


<%@ page contentType="text/html;charset=UTF-8" %>
<html>
<head>
	<title>上传图片</title>
	<meta name="decorator" content="default"/>
	<script type="text/javascript">
		$(document).ready(function() {
			$("#name").focus();
			$("#inputForm").validate({
				submitHandler: function(form){
					loading('正在提交,请稍等...');
					form.submit();
				},
				errorContainer: "#messageBox",
				errorPlacement: function(error, element) {
					$("#messageBox").text("输入有误,请先更正。");
					if (element.is(":checkbox")||element.is(":radio")||element.parent().is(".input-append")){
						error.appendTo(element.parent().parent());
					} else {
						error.insertAfter(element);
					}
				}
			});
		});
		
	</script>
</head>
<body>		
	<form:form id="inputForm" modelAttribute="picture" action="${pageContext.request.contextPath}/sys/picture/save" method="post" class="form-horizontal" enctype="multipart/form-data">	
		<div class="control-group">
			<label class="control-label">上传图片:</label>
			<div class="controls">
				<input type="file" name="file" accept="image/png,image/jpeg" class="required" value="file"/>
				<span class="help-inline"><font color="red">*只支持JPG、PNG格式文件</font> </span>
			</div>
		</div>	
		
		<div class="form-actions">
			<input id="btnSubmit" class="btn btn-primary" type="submit" value="保 存"/>
			<input id="btnCancel" class="btn" type="button" value="返 回" οnclick="history.go(-1)"/> 
		</div>
	</form:form>
	
</body>
</html>


三、controller


/**
 * 上传图片Controller
 * @author 丽杰
 * @version 2017-03-04
 *
 */
@Controller
@RequestMapping(value = "${adminPath}/sys/picture")
public class PictureController{

  private File file;
  
  public File getFile() {
  return file;
  }

  public void setFile(File file) {
    this.file = file;
  }
  
  //-----------保存+文件上传-------start--------

  @RequestMapping(value = "save")
  public String save(@RequestParam("file") CommonsMultipartFile file,PictureEntity pictureEntity, Model model, RedirectAttributes redirectAttributes)throws IOException {
    
    //1、生成文件的id
    String fileId = UUID.randomUUID().toString().replaceAll("-", "");
    
    //2、获得文件的真实名字
    String fileName=file.getOriginalFilename();
    
    //3、获取文件的后缀
    String suffix=fileName.substring(fileName.lastIndexOf(".")+1);
    
    //4、拼接文件名:ID+"."+后缀
    String jointName = fileId+"."+suffix;
    
    //5、判断系统的类型并找到图片文件存放的位置
    String dir =null;
    if(System.getProperty("os.name").toLowerCase().indexOf("windows") >= 0){
      dir=Global.getConfig("picture_windows");
    }
    if(System.getProperty("os.name").toLowerCase().indexOf("linux") >= 0){
      dir=Global.getConfig("picture_linux");
    }
    
    //6、判断picture文件夹是否存在,不存在,则创建
    File dirFile=new File(dir);
    if(!dirFile.exists()){
      dirFile.mkdirs();
    }
    
    //7、获得上传路径以及拼接上传文件名
    String path=dir+jointName;
    
    //8、上传
    File newFile=new File(path);
    file.transferTo(newFile);
    
    addMessage(redirectAttributes, "保存图片成功!");
    return "redirect:" + adminPath + "/sys/picture/";
  }
  //-----------保存+文件上传-------end--------
}

四、学习心得


1、从配置文件中读取路径其实用Global.getConfig就可以了。

2、input的accept="image/png,image/jpeg" 属性可以控制上传文件的类型。





  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 18
    评论
评论 18
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值