servlet文件上传
public String uploadFile(HttpServletRequest request){
try {
DiskFileItemFactory factory= new DiskFileItemFactory();
ServletFileUpload upload= new ServletFileUpload(factory);
List<FileItem> list = upload.parseRequest(request);
String encoding=request.getCharacterEncoding();
upload.setHeaderEncoding(encoding);
upload.setFileSizeMax(fileMaxSize);
for(FileItem fileItem : list){
String fileName = fileItem.getFieldName();
if(fileItem.isFormField()){
if("send".equals(fileName)){
edto.setSend(fileItem.getString(encoding));
}
if("incept".equals(fileName)){
edto.setIncept(fileItem.getString(encoding));
}
if("theme".equals(fileName)){
edto.setTheme(fileItem.getString(encoding));
}
if("letter".equals(fileName)){
edto.setLetter(fileItem.getString(encoding));
}
}
else{
if("file".equals(fileName)){
String sourceFilePath = fileItem.getName();
if(sourceFilePath!=""){
if(fileItem.getSize()>fileMaxSize){
return "文件过大,不能上传!";
}
HttpSession session =request.getSession();
String serverPath = session.getServletContext().getRealPath("");
String savePath = serverPath + "\\userfile";
String saveFileName =GetSaveFileName.getFileName(edto.getIncept(),edto.getSend(),sourceFilePath);
InputStream in = fileItem.getInputStream();
edto.setSaveFileName(saveFileName);
this.saveFile(savePath,saveFileName, in);
}
}
}
}
保存上传的文件到服务器:
//保存文件到服务器
private void saveFile(String savePath,String saveFileName,InputStream in) throws IOException{
File file=new File(savePath);
if(!file.exists()){
file.mkdirs();
}
FileOutputStream out =new FileOutputStream(savePath+"\"+saveFileName);
byte [] b =new byte[1024];
int len = in.read(b);
while(len!=-1){
out.write(b, 0, len);
out.flush();
len = in.read(b);
}
out.close();
in.close();
} 悲剧了。。。