/**
* 上传之后的文件名
*/
private String storageFileName;
@Action(value="enrollTablefileUpload",results={@Result(name="success",type="redirect",location="/match/match/attachment"),@Result(name="failure",type="redirect",location="/match/match/attachment/failure")},interceptorRefs={@InterceptorRef("fileUploadStack")})
public String enrollTablefileUpload() {
long start = System.currentTimeMillis();
Map<String, Object> map = new HashMap<String, Object>();
storageFileName = uploadFileName;
System.out.println("上传的文件名称"+storageFileName);
boolean isok= matchService.addMatchTable(mid, uploadFileName);
path = ServletActionContext.getServletContext().getRealPath("/upload");
String separator = File.separator;
// 创建要写入的文件
File storageFile = new File(ServletActionContext.getServletContext()
.getRealPath("/upload") + separator + storageFileName);
boolean isok2 = copy(upload, storageFile);
long end = System.currentTimeMillis();
System.out.println("消耗时间"+(end-start)+"ms");
System.out.println("更新附件"+isok+"\n"+"复制文件"+isok2+"俱乐部编号"+mid);
if(isok&&isok2){
return "success";
}
return "failure";
}
/**
* 上传文件的主要方法
*
* @param src
* @param dst
* @return
*/
public boolean copy(File src, File dst) {
try {
InputStream in = null;
OutputStream out = null;
try {
in = new BufferedInputStream(new FileInputStream(src),BUFFER_SIZE);
out = new BufferedOutputStream(new FileOutputStream(dst), BUFFER_SIZE);
byte[] buffer = new byte[BUFFER_SIZE];
while (in.read(buffer) > 0) {
out.write(buffer);
}
} finally {
if (null != in) {
in.close();
}
if (null != out) {
out.close();
}
}
} catch (Exception e) {
e.printStackTrace();
}
return true;
}
public static String getExtention(String fileName){
int pos = fileName.lastIndexOf(".");
return fileName.substring(pos);
}
下面这种方式比较简单的实现文件上传
/**
* 报名成功后,将所有信息返回界面
* @return
* @throws IOException
*/
@RequestMapping(value="/enroll",method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
@ResponseBody
public String enroll(HttpServletRequest request,HttpServletResponse response,@RequestParam MultipartFile[] liftImage) {
long startTime = System.currentTimeMillis();
for (MultipartFile image : liftImage) {
String name=null;
if(image.isEmpty()){
log.debug("{}",IceLog.printLog(startTime, "上传生活照片", "没有上传照片,为空"));
}else{
long size = image.getSize();
name = image.getName();
log.debug("{}",IceLog.printLog(startTime, "上传生活照片", "成功上传照片",size,name));
}
String realPath = request.getSession().getServletContext().getRealPath("/");
try {
FileUtils.copyInputStreamToFile(image.getInputStream(), new File(realPath, image.getOriginalFilename()));
log.debug("{}",IceLog.printLog(startTime, "上传生活照片", "照片路径为"+realPath+image.getOriginalFilename()));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}