📄 fileupload.java
字号:
package com.mvc.Beans;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.servlet.http.*;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.util.FileCopyUtils;
import org.springframework.validation.*;
import org.springframework.web.bind.*;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.multipart.support.ByteArrayMultipartFileEditor;
import org.springframework.web.servlet.*;
import org.springframework.web.servlet.mvc.*;
import com.mvc.form.*;
public class fileUpload extends SimpleFormController{
public Log log=LogFactory.getLog(fileUpload.class);
public String storepath; //上传文件路径
public String getStorepath() {
return storepath;
}
public void setStorepath(String storepath) {
this.storepath = storepath;
}
public fileUpload(){ //构造函数
setCommandClass(uploadForm.class);
}
@Override
protected ModelAndView onSubmit(HttpServletRequest request,
HttpServletResponse response, Object command, BindException errors)
throws Exception {
// TODO Auto-generated method stub
//uploadForm upload=(uploadForm) command;
//byte[] uploadfile=upload.getFile();
MultipartHttpServletRequest multipart=(MultipartHttpServletRequest)request;
CommonsMultipartFile file=(CommonsMultipartFile)multipart.getFile("file");
String storepath=this.storepath;
File path=new File(storepath);
if(!path.exists()){
path.mkdirs();
}
String oldfile=new String(file.getOriginalFilename().getBytes("GBK"),"UTF-8");
int pos=oldfile.lastIndexOf("."); //获取文件后缀名
String ext=oldfile.substring(pos,oldfile.length());
Date dt=new Date(System.currentTimeMillis()); //获取上传文件时间
SimpleDateFormat fmt=new SimpleDateFormat("yyyyMMddHHmmssSSS");
String newfile=fmt.format(dt)+ext;
if(log.isDebugEnabled()){
log.debug("uploading file to: "+storepath+System.getProperty("file.separator")+newfile);
}
File uploadpath=new File(storepath+System.getProperty("file.separator")+newfile);
BufferedOutputStream buffer=new BufferedOutputStream(new FileOutputStream(uploadpath));
FileCopyUtils.copy(file.getInputStream(), buffer);
System.out.println("************");
System.out.println(uploadpath.getAbsolutePath());
//System.out.println(uploadfile.length);
System.out.println("************");
return new ModelAndView(getSuccessView());
}
@Override
protected void initBinder(HttpServletRequest request,
ServletRequestDataBinder binder) throws Exception {
// TODO Auto-generated method stub
super.initBinder(request, binder);
binder.registerCustomEditor(byte[].class,new ByteArrayMultipartFileEditor());
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -