复习电商笔记-13-图片上传(前后端)

 

图片上传

 

 

上传图片有什么问题?

1)文件大小限定,网络传输有限,控制用户上传文件的大小。

2)文档格式,通过文件后缀名判断是否图片类型。

3)文件内容,检验是否是图片,防止恶意用户上传图片木马。如何检查?获取图片的height和width。javaAPI直接提供方法。

4)及时清理文件。它使用的是apache的common文件上传jar。Apache文件上传的原理是先把上传的文件写临时文件,写完后保存到用户指定的目录。这样在文件上传的过程中会产生临时文件,上传完,需要及时清除临时文件。

 

 

执行过程

KindEditor组件是js自身无法完成文件上传,必须依托jsp/servlet/controller。它需要将一个jsp/servlet/controller放入到项目工程中,在引入的页面中加入KindEditor,它的图片工具栏会调用这个jsp,然后配置这个jsp需要再自己写一个对应的controller来完成图片上传,判断、保存。

在common.js中绑定图片上传触发事件,P26行,调用uploadJson : '/pic/upload'。调用PicUploadController.java。

点击“图片上传“,选择本地文件,可选择多个图片,上传完成之后,拿到上传图片的url,在商品图片后面,显示出一个一个图片。它是富文本编辑器中自带的功能。

 

 

准备过程

第一步:在class中加picFileUpload

<tr>
    <td>商品图片:</td>
    <td>
	 <a href="javascript:void(0)" class="easyui-linkbutton picFileUpload">上传图片</a>
	 <input type="hidden" name="image"/>
    </td>
</tr>

在index.jsp中引入common.js。在common.js中初始化initPicUpload,绑定onclick事件,引入KindEditor控件的多图片文件上传插件loadPlugin。具体写法参见KindEditor的示例。

 

第二步:加上env.properties扩展(参见上面的准备工作)

REPOSITORY_PATH=c:\\jt-upload
IMAGE_BASE_URL=http://image.jt.com

第三步:在springmvc-config.xml中增加文件上传解析器

<!-- 定义文件上传解析器 -->
	<bean id="multipartResolver"
		class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
		<!-- 设定默认编码 -->
		<property name="defaultEncoding" value="UTF-8"></property>
		<!-- 设定文件上传的最大值5MB,10*1024*1024 -->
		<property name="maxUploadSize" value="10485760"></property>
	</bean>

第四步:在jt-parent/pom.xml引入jar支持

<!-- 文件上传组件 -->
	<commons-fileupload.version>1.3.1</commons-fileupload.version>
        <dependency>
			<groupId>commons-fileupload</groupId>
			<artifactId>commons-fileupload</artifactId>
			<version>${commons-fileupload.version}</version>
		</dependency>

第五步:引用公用包中的

 

 

PicUploadResult

KindEditor回显图片时有json格式要求,下面的对象就是按这个格式要求实现

package com.jt.common.vo;

public class PicUploadResult {
	//图片上传错误不能抛出,抛出就无法进行jsp页面回调,所以设置这个标识,0表示无异常,1代表异常
    private Integer error=0;
    private String url;
    private String width;
    private String height;

    public Integer getError() {
        return error;
    }
    public void setError(Integer error) {
        this.error = error;
    }
    public String getUrl() {
        return url;
    }
    public void setUrl(String url) {
        this.url = url;
    }
    public String getWidth() {
        return width;
    }
    public void setWidth(String width) {
        this.width = width;
    }
    public String getHeight() {
        return height;
    }
    public void setHeight(String height) {
        this.height = height;
    }
}

 

 

PicUploadController

点击“上传图片按钮“调用PictureController的方法

package com.jt.manage.Controller;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.annotation.Resource;
import javax.imageio.ImageIO;

import org.apache.commons.lang3.RandomUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.jt.base.service.PropertieService;
import com.jt.common.vo.PicUploadResult;

/**
 * 图片上传下载
 */
@Controller
@RequestMapping(value="/pic")
public class PicUploadController {
	
	@Resource	//将属性封装成一个service,这样就可以在controller中使用
	private PropertieService propertieService;
	
	
	/**
	 * 图片上传
	 * @param uploadFile
	 * @return
	 * @throws IOException 
	 */
	@RequestMapping(value="/upload")
	@ResponseBody
	public PicUploadResult upload(MultipartFile uploadFile) throws IOException{
		PicUploadResult result = new PicUploadResult();
		//获取文件名称
		String filename = uploadFile.getOriginalFilename();
		//检查文件类型是否为图片
//正则:^正则表达式开始,. 匹配任何单个字符;?0到1个字符串匹配多个字符,*0到多个子串匹配,()分组,|或者,$正则表达式结束
		if(!filename.matches("^*\\.(jpg|png|jpeg|gif)$")){
			result.setError(1);
		}else{
			//判断是否为木马
			try{
				BufferedImage image = ImageIO.read(uploadFile.getInputStream());
				result.setHeight(image.getHeight()+"");
				result.setWidth(image.getWidth()+"");
            }catch(Exception e){
				result.setError(1);
			}
			if(result.getError() == 0){
				//创建文件目录(按照年月日分文件夹)
				String path = new SimpleDateFormat("yyyyMMdd").format(new Date());
				//获取文件后缀
				String fileSuffix = filename.substring(filename.lastIndexOf("."));
				//生成新的文件名(当前时间加三位随机数)
				String _filename = System.currentTimeMillis()+""+RandomUtils.nextInt(100, 999);
				//设置回显url
				result.setUrl(propertieService.IMAGE_BASE_URL+File.separator+"images"+File.separator+path+File.separator+_filename+fileSuffix);
				//生成上传目录
				File dir = new File(propertieService.REPOSITORY_PATH+File.separator+"images"+File.separator+path);
				if(!dir.exists())dir.mkdirs();
				//上传到服务器
				File newfile = new File(propertieService.REPOSITORY_PATH+File.separator+"images"+File.separator+path+File.separator+_filename+fileSuffix);
				uploadFile.transferTo(newfile);
			}
		}
		return result;
	}
	
}

第六步:上传图片

图片上传成功,但显示时报错,如下图所示:

 

 

本地的hosts没有配置

支持image.jt.com转换为ip地址127.0.0.1

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值