前端上传图片到服务器
前端上传代码:
<!DOCTYPE html>
<html>
<head>
<meta charset=”UTF-8″>
<title>文件上传</title>
</head>
<body>
<form action=”upload.do” method=”post” enctype=”multipart/form-data”>
<input name=”file” type=”file”>
<input type=”submit” value=”上传文件”>
</form>
</body>
</html>
服务端代码:
package cn.te.spring.controller;
import java.io.File;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
@Controller
public class UploadController {
@RequestMapping(“/upload.do”)
public String handleUpload(HttpServletRequest request,
@RequestParam(“file”)CommonsMultipartFile file) throws IllegalStateException, IOException {
//CommonsMultipartFile是springmvc封装的上传数据
//确定文件名
String fileName=”upFile.exe”;
//获取文件夹的真实路径
String folderPath=request.getServletContext().getRealPath(“upload”);
//确定文件夹,必须是webapp下面的某个文件夹,否则用户访问不到
File parentFile=new File(folderPath);
//确定上传的文件存储到的目标文件
File dest=new File(parentFile,fileName);
//将文件上传的数据进行存储
file.transferTo(dest);
return null;
}
}