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

Java文件上传(在SpringMVC模式下,从本地上传到服务器)

2013-12-19 10:43 381 查看
<html>页面部分重要代码

<form method="post" enctype="multipart/form-data" action="toUpLoadFile">

请选择库房文件:<input type="file" name="excelFile">

<input type="submit" value="导入" onclick="return impExcel();"/>

</form>

Java类

import java.io.File;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.InputStream;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FileUtils;

import org.apache.struts2.ServletActionContext;

import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.multipart.MultipartFile;

import com.opensymphony.xwork2.ActionContext;

@Controller

public class UpLoadFile {

private MultipartFile excelFile;// 得到上传的文件

private String excelFileContentType;// 得到文件的类型

private String excelFileFileName;// 得到文件的名称

public MultipartFile getExcelFile() {

return excelFile;

}

public void setExcelFile(MultipartFile excelFile) {

this.excelFile = excelFile;

}

public String getExcelFileContentType() {

return excelFileContentType;

}

public void setExcelFileContentType(String excelFileContentType) {

this.excelFileContentType = excelFileContentType;

}

public String getExcelFileFileName() {

return excelFileFileName;

}

public void setExcelFileFileName(String excelFileFileName) {

this.excelFileFileName = excelFileFileName;

}

@RequestMapping("/toUpLoadFile")

public String execute(MultipartFile excelFile,HttpServletRequest req) throws Exception {//使用MultipartFile 在SpringMVC下  不能直接用File

if (excelFile != null) {

System.out.println(excelFile.getName()+"--"+excelFile.getSize());

String filename=excelFile.getOriginalFilename();

SaveFileFromInputStream(excelFile.getInputStream(),req.getRealPath("resources/importExcel"),filename);//保存到服务器的路径

List<StoreEntity> entitys = readFileInfo(req.getRealPath("resources/importExcel")+"/"+filename);

ActionContext.getContext().put("message", "上传成功");

}

return "success";

}

private List<StoreEntity> readFileInfo(String string) {

// TODO Auto-generated method stub

return null;

}

//将MultipartFile 转换为File

public void SaveFileFromInputStream(InputStream stream,String path,String savefile) throws IOException

{

FileOutputStream fs=new FileOutputStream( path + "/"+ savefile);

System.out.println("------------"+path + "/"+ savefile);

byte[] buffer =new byte[1024*1024];

int bytesum = 0;

int byteread = 0;

while ((byteread=stream.read(buffer))!=-1)

{

bytesum+=byteread;

fs.write(buffer,0,byteread);

fs.flush();

}

fs.close();

stream.close();

}

}

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