`

Struts2上传图片和注意事项

阅读更多

Struts2上传图片和注意事项

 

1.必须有拦截器:

(1).可放在公共拦截器中
<interceptor-ref name="fileUpload"/>
(2).可放在action中
<!-- 配置名字为fileUpload的拦截器 -->
<interceptor-ref name="fileUpload">
 	<!-- 配置允许上传的文件类型 -->
  	<param name="allowedTypes">image/bmp,image/png,image/gif,
     	image/jpeg,image/pjpeg,image/x-png</param>
 	<!-- 配置允许上传文件的大小(单位字节) -->
 	<param name="maximumSize">104857600</param>
</interceptor-ref>
<!-- defaultStack必须配置在fileUpload后面 -->
<interceptor-ref name="defaultStack"></interceptor-ref>

 
    
 
    
 

 

2.修改限制的大小:

<constant name="struts.multipart.maxSize" value="10485760" />
或
struts.multipart.maxSize=104857600

注:不用改的地方:

struts.multipart.parser=jakarta
struts.multipart.saveDir=??

 

3.页面的form中需要加:

enctype="multipart/form-data"
 

 

4.页面的上传域如下:(注意name属性)

<input type="file" name="image" />
 

 

5.action中必须加的属性:(注意添加set/get方法)

private File image; // 上传图片获取的File对象
private String imageFileName; //上传图片获取的图片名字
private String imageContentType; //上传图片获取的图片类型
 

上传工具类:

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Calendar;


public class UploadFileUtil {
	
	
	/**
	 * 上传图片的方法
	 * @param imageFile  // 上传图片获取的File对象
	 * @param imageName	 //上传图片获取的图片名字
	 * @return
	 * @throws IOException
	 */
	public static String uploadImage(File imageFile, String imageName ) throws IOException {
		
		int random = (int)(Math.random()*900)+100;
		/*创建输入流*/  
		InputStream is = new FileInputStream(imageFile);  
		/*设置上传目录*/  
		String path = "G:\\resource";
		Calendar cal=Calendar.getInstance();
		String imageUrlPath = "images" + File.separator + cal.get(Calendar.YEAR) + File.separator + (cal.get(Calendar.MONTH)+1) + File.separator 
				+  cal.get(Calendar.DAY_OF_MONTH);
		String imagePath = path + File.separator + imageUrlPath;
		File file = new File(imagePath);
		if (!file.exists()) {
			file.mkdirs();
		}
		/*设置目标文件*/  
		String targetImageName = "" + cal.get(Calendar.HOUR) + cal.get(Calendar.MINUTE) + cal.get(Calendar.SECOND) 
				+ cal.get(Calendar.MILLISECOND) + random + imageName.substring(imageName.indexOf("."));
		File target = new File(imagePath + File.separator + targetImageName);
		/*创建输出流*/  
		OutputStream os = new FileOutputStream(target);  
		byte[] buffer = new byte[1024];  
		int length = 0;  
		while ((length = is.read(buffer)) > 0) {  
		    os.write(buffer, 0, length);  
		}  
		is.close();  
		os.close();  
		return imageUrlPath + File.separator + targetImageName;
	}

}

  
     
 

参考:

struts2实现文件上传(配置拦截器)

struts2上传文件问题汇总

struts文件上传,获取文件名和文件类型  

  • 大小: 11 KB
  • 大小: 24.1 KB
  • 大小: 22.4 KB
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics