Java Struts图片上传至指定文件夹并显示图片功能

网友投稿 251 2023-04-22


Java Struts图片上传至指定文件夹并显示图片功能

继上一次利用Servlet实现图片上传,这次利用基于MVC的Struts框架,封装了Servlet并简化了jsP页面跳转。

JSP上传页面

上传一定要为form加上enctype="multipart/form-data",表示提交的数据时二进制的

并且必须是method="post"

<%@ page language="java" contentType="text/html; charset=utf-8"

pageEncoding="utf-8"%>

<%@taglib prefix="s" uri="/struts-tags"%>

struts.xml配置(maven项目放在resources)

"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"

"http://struts.apache.org/dtds/struts-2.3.dtd">

      设置文件上传最大值

/fail.jsp

/success.jsp

TestStruts.java控制类

一定要提供三个属性

File img;

String imgFileName;

String imgContentType;

然后为这3个属性提供getter setter方法

package com.controller;

import java.io.File;

import java.io.IOException;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionContext;

import com.opensymphony.xwork2.ActionSupport;

public class TestStruts extends ActionSupport{

private File img;

private String imgFileName;

private String imgContentType;

public File getImg(){

return img;

}

public String getimgFileName(){

return imgFileName;

}

public String getImgContentType(){

return imgContentType;

}

public void setImg(File img){

this.img = img;

}

public void setImgFileName(String imgFileName){

this.imgFileName = imgFileName;

}

public void setImgFileContentType(String imgContentType){

this.imgContentType = imgContentType;

}

@SuppressWarnings("unchecked")

public String logintest() throws IOUQcdTException{

Map p = ActionContext.getContext().getSession();

p.put("imgFileName", imgFileName);

File f = new File("D://imagebystruts");

if (!f.exists()) {

f.mkdir();

}

FileUtils.copyFile(img, new File(f, imgFileName));

return "success";

}

}

Tomcat中server.xml文件配置虚拟路径

success.jsp显示图片

<%@ page language="java" contentType="text/html; charset=utf-8"

pageEncoding="utf-8"%>

<%@ taglib prefix="s" uri="/struts-tags" %>

总结

以上所述是给大家介绍的Java Struts图片上传至指定文件夹并显示图片功能,希望对大家有所帮助,如果大家有任何疑问请给我留言,会及时回复大家的。在此也非常感谢大家对我们网站的支持!


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:三步轻松搭建springMVC框架
下一篇:java算法之二分查找法的实例详解
相关文章

 发表评论

暂时没有评论,来抢沙发吧~