form表单部分:
<form action="user/save" method="post" enctype="multipart/form-data">
<label><span>用户名:</span><input type="text" name="username"></label><br>
<label><span>密码:</span><input type="password" name="password"></label><br>
<label><span>上传图片:</span><input type="file" ></label><br>
<label><input type="submit"></label>
</form>
控制层代码:
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import com.hd.model.User;
import com.hd.service.IUserService;
@Controller
@RequestMapping("/user")
public class UserControl {
@Autowired
private IUserService iu;
@RequestMapping("/save")
//@RequestParam(value="file", required = false) MultipartFile file,
public String save(User user,@RequestParam(value="file", required = false) MultipartFile file){
String newname=file.getOriginalFilename();
if(newname!=null&&newname.length()>0){
user.setPpath(newname);
}
iu.save(user);
if(file.isEmpty()){
System.out.println("附件为空");
}else{
System.out.println(file);
}
return "/home.jsp";
}
}
spring-mvc xml配置:
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="UTF-8" />
</bean>
jar包: