文件上传下载

时间:2021-12-09 20:58:29

struts2 + spring  action中文件上传和下载

文件上传:

1、保存到Tomcat中

public String uploadFile() throws Exception{

String abslutePath = ServletActionContext.getServletContext().getRealPath(savePath); //读取struts配置文件中的路径

File targetPath = new File(abslutePath);
if(!targetPath.exists()){
targetPath.mkdirs();
}

String newFileName = createFileName();
String targetFile = abslutePath + "\\" + newFileName;
FileInputStream fis = new FileInputStream(headicon);
FileOutputStream fos = new FileOutputStream(targetFile);
byte[] bytes = new byte[1024];
int n;
while((n=fis.read(bytes)) != -1){
fos.write(bytes, 0, n);
}
fis.close();
fos.close();

user.setHeadicon(savePath+"/"+newFileName);
getResponse().setContentType("text/html;charset=UTF-8");
getResponse().setCharacterEncoding("UTF-8");
        java.io.PrintWriter out = getResponse().getWriter();
        out.println("<script language='javascript'>");
        out.println("window.alert('修改成功!');");
        out.println("window.location.href = 'individualCenterAction_load.action';");
        out.println("</script>");
        out.flush();  
        out.close(); 
return null;
}

private String createFileName(){
String extension = headiconFileName.substring(headiconFileName.lastIndexOf("."));
return user.getLoginname()+extension;

}

2、保存到本地磁盘中(推荐此种做法)

public String uploadFile() throws Exception{
File targetPath = new File(savePath);
if(!targetPath.exists()){
targetPath.mkdirs();
}

FileInputStream fi = new FileInputStream(headicon);
FileOutputStream fo = new FileOutputStream(targetPath+"\\"+createFileName());
byte[] bytes = new byte[1024];
int n = -1;

while((n = fi.read(bytes)) != -1){
fo.write(bytes,0,n);
}
fi.close();
fo.close();
   getRequest().setAttribute("tips", "true");
return load();
}

private String createFileName(){
String extension = headiconFileName.substring(headiconFileName.lastIndexOf("."));
return user.getLoginname()+extension;
}

文件下载:

public String downloadFile() throws IOException{
HttpServletResponse response = getResponse();
String photoPath = savePath+"\\"+user.getHeadicon();
File file = new File(photoPath);
        // 取得文件名。
        String filename = file.getName();
        // 取得文件的后缀名。
        //String ext = filename.substring(filename.lastIndexOf(".") + 1).toUpperCase();


        // 以流的形式下载文件。
        InputStream fis = new BufferedInputStream(new FileInputStream(file));
        byte[] buffer = new byte[fis.available()];
        fis.read(buffer);
        fis.close();
        // 清空response
        response.reset();
        // 设置response的Header
        response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes("utf-8"),"ISO-8859-1"));
        response.addHeader("Content-Length", "" + file.length());
        OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
        response.setContentType("image/gif");
        toClient.write(buffer);
        toClient.flush();
        toClient.close();
return null;
}

补充(未完善):

public void test() {
File file = new File();
Date uplodDate = new Date();
String year = new SimpleDateFormat("yyyy").format(uploadDate);
String month = new SimpleDateFormat("MM").format(uploadDate);
String day = new SimpleDateFormat("dd").format(day);
file.getName();

File newFile = new File(uploadPath + "\\" + year + "\\" + month + "\\" + day + "\\" + file.getName());
FileWriter fw = new FileWriter(newFile);
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
String str = null;
while ((str = br.readLine()) != null) {
fw.write(str);
}



uploadPath
}

show{

}

校验补充:

//剔除两边空格
function trim(str){
var regLeft = /^\s+/;
var regRight = /\s+$/;
return str.replace(regLeft,"").replace(regRight,"");
}

function checkForm(){
var uploadFile = document.getElementById("upload").value;
if(trim(uploadFile).length == 0){
if(!confirm("确定不更新头像图片?")){
return false; 
}
}
//判断是否是图片 - strFilter必须是小写列举
       var alltypes = ".gif";
var objtype = uploadFile.substring(uploadFile.lastIndexOf(".")).toLowerCase();
if(alltypes.indexOf(objtype) < 0){
alert("请选择gif格式文件!");
return false;
}
return true;
}

input type="file" name="headicon" id="upload"/>