struts2中的文件上传

本文介绍了一个使用Struts2框架实现的头像上传功能的具体实现过程,包括前端表单设计、文件上传处理及服务器端文件存储等关键步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

最近项目中有个头像上传的业务,前端用form表单提交,后台是Struts2接收并保存文件,以下是代码

html代码

<b>验证表单</b>  
<form action="http://localhost:8080/YCAPP/uploadPicture.action" method="post" enctype="multipart/form-data" id="uploadForm">  
<input type="text" name="userId" /><br/>
 <input id="file" type="file" name="file" οnchange="setValue()"/> <br/>
 <input if="name" type="text" name="fileName" /><br/>  
<input type="submit"  value="提交">  
</form>  
<hr/>  
<h1> 用户头像</h1>
<img id="headimg"  src=""/>
<button οnclick="getPhoto()">查询头像</button>
</body> 

 提交要用到的js函数

function setValue(){
	var fileName = document.getElementById("file").value;
	document.getElementsByName("fileName")[0].value=fileName;
}
 function init(){  
      document.all.file1.focus();  
      var WshShell=new   ActiveXObject("WScript.Shell");  
      WshShell.sendKeys("C:\\WINDOWS\\System.dat");
 }   
$(document).ready(function(){  
	var fileName = document.getElementById("file").value;
    $('#uploadForm').ajaxForm({
		dataType:"jsonp",
		jsonp:"jsonpcallback", 
        success: processJson  
    });  
    function processJson(data){  
        alert("提交成功");  
    }  
});

在服务器端不能通过request得到输入流然后读取文件,之前我这做一个字节也读不到,后来才知道struts框架已经帮我们读取了,并生成了临时文件,这里直接通过处理请求的action类里面属性去得到文件就行啦

/**
 * this class it to handle some request of files,such as picture
 * 
 * @author ljh
 * 
 */
public class FileAction extends CommonAction {
	/**
	 * the file which was saved as tmp file by server,it was posted form web
	 * page
	 */
	private File file;
	/**
	 * the file name of file uploaded from web page
	 */
	private String fileName;
	/**
	 * this userId of user
	 */
	private String userId;

	public String getFileName() {
		return fileName;
	}

	public void setFileName(String fileName) {
		this.fileName = fileName;
	}

	public String getUserId() {
		return userId;
	}

	public void setUserId(String userId) {
		this.userId = userId;
	}

	public File getFile() {
		return file;
	}

	public void setFile(File file) {
		this.file = file;
	}

	/**
	 *this method is called to post picture of one user
	 */
	public void uploadPicture() {
		HttpServletResponse response = getResponse();
		HttpServletRequest request = getRequest();
		FileService fileService = new FileService();
		JSONObject json = new JSONObject();
		try {
			if(userId!=null){
				String relativPath = request.getRealPath("/");
				String filePath = fileService.storeFileService(relativPath,userId, fileName, file);
				if(filePath!=null){
					boolean result=fileService.storeFilePathToDBService(userId, filePath);
					if(result==true){
						json.put(Result.RESULT, Result.USERINFO_PHOTOUPLOAD_OK);
					}else{
						json.put(Result.RESULT, Result.USERINFO_PHOTOUPLOAD_FAIL);
					}
				}else{
					json.put(Result.RESULT, Result.USERINFO_PHOTOUPLOAD_FAIL);
				}
			}else{
				json.put(Result.RESULT, Result.USERINFO_PHOTOUPLOAD_FAIL);
			}
		} catch (Exception e) {
			e.printStackTrace();
			try {
				json.put(Result.RESULT, Result.USERINFO_PHOTOUPLOAD_FAIL);
			} catch (JSONException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			
		}
		returnResult(request, response, json.toString());

	}

}

 下面是FileService类

/**
 * the fileService offer some file operation methods
 * @author ljh
 *
 */
public class FileService {
	/**
	 * the ROOTPATH 
	 */
	public static final String ROOTPATH="data\\userInfo\\";
	/**
	 * this method will store the temfile upload from one user,and it will creat
	 * a folder named with the userId if it is not exist
	 * @param userId
	 * @param fileName
	 * @param tmpfile
	 * @return
	 */
	public String storeFileService(String relativPath,String userId, String fileName,File tmpfile){
		try {
			File filePath = new File(relativPath+ROOTPATH+userId+"\\photo");
			if(!filePath.exists()){
				filePath.mkdirs();
			}
			int index=fileName.lastIndexOf(".");
			fileName="photo"+fileName.substring(index);
			String fileWithPath = relativPath+ROOTPATH+userId+"\\photo\\"+fileName;
			System.out.println("filepath:"+fileWithPath);
			File file = new File(fileWithPath);
			FileInputStream fileInputStream = new FileInputStream(tmpfile);
			FileOutputStream fileOutputStream = new FileOutputStream(file);
			byte[] buffer = new byte[1024];
			int length = 0;
			while (-1 != (length = fileInputStream.read(buffer, 0, buffer.length))) {
				fileOutputStream.write(buffer);
			}
			fileOutputStream.close();
			fileInputStream.close();
			return "data/userInfo/"+userId+"/photo/"+fileName;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
		
	}
	/**
	 * this method 
	 * @param userId
	 * @param filePath
	 * @return
	 */
	public boolean storeFilePathToDBService(String userId, String filePath){
		UserInfoService userInfoService = new UserInfoService();
		User user = new User();
		user.setUserId(userId);
		user.setPhoto(filePath);
		return userInfoService.updataUserInfoService(user);
	}
	public void deleteFileService(String userId,String filePath){
		
	}
	/**
	 * test code
	 * @param args
	 */
	public static void main(String[] args) {
		FileService f = new FileService();
		//String filepath=f.storeFileService("1", "test.txt", new File("D:/ycapp/tmpfile"));
		//System.out.println("is ok?:"+f.storeFilePathToDBService("1", filepath));
		
	}
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值