您的位置:首页 > Web前端 > HTML

html + servlet 实现文件的上传

2016-07-08 10:47 253 查看
程序要求:

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;
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: