package
cn.zifangsky.controller;
import
java.io.File;
import
java.io.IOException;
import
javax.servlet.http.HttpServletRequest;
import
org.apache.commons.io.FileUtils;
import
org.springframework.stereotype.Controller;
import
org.springframework.web.bind.annotation.RequestMapping;
import
org.springframework.web.bind.annotation.RequestMethod;
import
org.springframework.web.bind.annotation.RequestParam;
import
org.springframework.web.multipart.MultipartFile;
import
org.springframework.web.servlet.ModelAndView;
import
cn.zifangsky.model.User;
import
cn.zifangsky.utils.StringUtile;
@Controller
public
class
UploadController {
@RequestMapping
(value =
"/form"
)
public
ModelAndView form() {
ModelAndView modelAndView =
new
ModelAndView(
"fileupload"
,
"user"
,
new
User());
return
modelAndView;
}
@RequestMapping
(value =
"/upload"
, method = RequestMethod.POST)
public
ModelAndView upload(User user,
@RequestParam
(
"file"
) MultipartFile tmpFile, HttpServletRequest request) {
ModelAndView modelAndView =
new
ModelAndView(
"fileupload"
);
if
(tmpFile !=
null
) {
String targetDirectory = request.getSession().getServletContext().getRealPath(
"/uploads"
);
String tmpFileName = tmpFile.getOriginalFilename();
int
dot = tmpFileName.lastIndexOf(
'.'
);
String ext =
""
;
if
((dot > -
1
) && (dot < (tmpFileName.length() -
1
))) {
ext = tmpFileName.substring(dot +
1
);
}
if
(
"png"
.equalsIgnoreCase(ext) ||
"jpg"
.equalsIgnoreCase(ext) ||
"gif"
.equalsIgnoreCase(ext)) {
String targetFileName = StringUtile.renameFileName(tmpFileName);
File target =
new
File(targetDirectory, targetFileName);
try
{
FileUtils.copyInputStreamToFile(tmpFile.getInputStream(), target);
}
catch
(IOException e) {
e.printStackTrace();
}
User u =
new
User();
u.setUserName(user.getUserName());
u.setLogoSrc(request.getContextPath() +
"/uploads/"
+ targetFileName);
modelAndView.addObject(
"u"
, u);
}
return
modelAndView;
}
return
modelAndView;
}
}