使用Struts2做一个图片上传的功能

1.表单要以二进制的方式提交,必须是post请求
enctype=“multipart/form-data”
在这里插入图片描述
2.表单中必须要有一个上传的控件
可以是<\input type=“file”>
也可以是

<s:file name="pic" cssClass="ui_input_txt02"/>

3.在action中必须要有两个字段

@Setter
	private File pic;
	@Setter
	private String picFileName;

字段的名称要个你在jsp页面file控件的名称有对应
4,使用FileUploadUtil中的方法上传(也可以自己写一个)

import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;

import java.io.File;
import java.util.UUID;

public class FileUploadUtil {
	public static final String suffix = "_small";

	public static String uploadFile(File file, String fileName) throws Exception {
		String uuid = UUID.randomUUID().toString();
		String fileType = fileName.substring(fileName.lastIndexOf("."));
		fileName = uuid + fileType;
		String path = ServletActionContext.getServletContext().getRealPath("/upload");

		File targetFile = new File(path, fileName);
		FileUtils.copyFile(file, targetFile);

		String smallImg = uuid + "_small" + fileType;
		File smallTargetFile = new File(path, smallImg);

		//Thumbnails.of(new File[] { targetFile }).scale(0.4000000059604645D).toFile(smallTargetFile);
		return "/upload/" + fileName;
	}

	public static void deleteFile(String imagePath) {
		String path = ServletActionContext.getServletContext().getRealPath("/") + imagePath;
		File file = new File(path);
		if (file.exists()) {
			file.delete();
		}
		path = ServletActionContext.getServletContext().getRealPath("/")
				+ imagePath.substring(0, imagePath.indexOf(".")) + "_small"
				+ imagePath.substring(imagePath.indexOf("."));
		file = new File(path);
		if (file.exists()) {
			file.delete();
		}
	}
}

5.保存时,直接调用方法即可

	String imagePath = FileUploadUtil.uploadFile(pic, picFileName);
	product.setImagePath(imagePath);

图片的压缩问题:使用thumbnailator
引入依赖

<dependency>
      <groupId>net.coobird</groupId>
      <artifactId>thumbnailator</artifactId>
      <version>0.4.8</version>
    </dependency>

在FileUploadUtil中使用,详见上面代码
这里注意页面上显示的应该是小图片,这样减少加载页面的资源
所以在保存时,大小图片的路径应该有已经的规律.例如:
_small.jpg之类,在实体类中直接提供get方法,就不必在增加一列
再做一下截取即可

 public String getSmallImagePath(){
        String fileName=imagePath.substring(0, imagePath.lastIndexOf("."))+"_small";
        String ext=imagePath.substring(imagePath.lastIndexOf("."),imagePath.length());
        return fileName+ext;
    }

页面上显示小图片即可

<td>
<img src="<s:property value="smallImagePath" />" class="list_img">
</td>

6.图片弹出框的小功能实现
这里使用的是fancybox插件,也可以使用其他的插件

引入相关的就是文件

<script type="text/javascript">
	$(function(){
	    $(".fc").fancybox();
	})
</script>
<td>
<%--title 表示对应的名称,href对应着大图的路径--%>
<a class="fc" href="<s:property value="imagePath" />" title="<s:property value="name" />">
<img src="<s:property value="smallImagePath" />" class="list_img">
</a>
</td>
发布了52 篇原创文章 · 获赞 2 · 访问量 225

猜你喜欢

转载自blog.csdn.net/weixin_41588751/article/details/103938068