您的位置:首页 > 编程语言 > Java开发

struts2中的文件上传

2015-12-20 17:23 316 查看

最近项目中有个头像上传的业务,前端用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" onchange="setValue()"/> <br/>
<input if="name" type="text" name="fileName" /><br/>
<input type="submit"  value="提交">
</form>
<hr/>
<h1> 用户头像</h1>
<img id="headimg"  src=""/>
<button onclick="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));

}
}

 

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: