html + servlet 实现文件的上传


程序要求:

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

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值