程序要求:
1.提供一个HTML文件,用户可以在相应 的表单中选择需要上传的文件;
2.编写一个名叫UploadServlet 的 Servlet 文件,主要功能是解析上面的HTML表单所提交的HTTP请求,把普通的文本域和文件域分离开来
3.UploadServlet 根据 web.xml 配置文件中的初始化参数确定好需要在web服务器上存放该文件的目录
import java.io.File;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
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;
@Controller
@RequestMapping("/pages")
public class UploadServlet {
@RequestMapping(value = "/add",method = {RequestMethod.POST})
//MultipartFile来自:org.springframework.web.multipart.MultipartFile;
public ModelAndView addGoods( HttpServletRequest request, HttpSession session,@RequestParam("file") MultipartFile file) {
ModelAndView mav = new ModelAndView();
if (!file.isEmpty()) {
String path = request.getContextPath() + "/jsp/";
String fileName = file.getOriginalFilename();
try {
String tomcatPath = "E:/GitProject"; //得到保存的路径
FileCopyUtils.copy(file.getBytes(), new File(tomcatPath +"/" + fileName));//FileCopyUtils来自org.springframework.util.FileCopyUtils
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
mav.setViewName("upload2");
return mav;
}
@RequestMapping(value = "/upload",method = {RequestMethod.GET})
public ModelAndView show(){
ModelAndView mav = new ModelAndView();
mav.setViewName("upload2");
return mav;
}
}