javaweb上传文件
上传文件的jsp中的部分
上传文件同样可以使用form表单向后端发请求,也可以使用 ajax向后端发请求
1. 通过form表单向后端发送请求
<form id="postForm" action="${pageContext.request.contextPath}/UploadServlet" method="post" enctype="multipart/form-data">
<div class="bbxx wrap">
<input type="text" id="side-profile-name" name="username" class="form-control">
<input type="file" id="example-file-input" name="avatar">
<button type="submit" class="btn btn-effect-ripple btn-primary">Save</button>
</div>
</form>
2. 通过ajax向后端发送请求
1.
$.ajax({
url : "${pageContext.request.contextPath}/UploadServlet",
type : "POST",
data : $( '#postForm').serialize(),
success : function(data) {
$( '#serverResponse').html(data);
},
error : function(data) {
$( '#serverResponse').html(data.status + " : " + data.statusText + " : " + data.responseText);
}
});
2.
var form = new FormData();
form.append("username","zxj");
form.append("avatar",file);
//var form = new FormData($("#postForm")[0]);
$.ajax({
url:"${pageContext.request.contextPath}/UploadServlet",
type:"post",
data:form,
processData:false,
contentType:false,
success:function(data){
console.log(data);
}
});
java部分
/**
* 上传文件的servlet
*/
public class UploadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public ChangeProfileServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//上传文件
try {
// request.getParameter(""); //创建磁盘文件工厂
DiskFileItemFactory fileItemFactory = new DiskFileItemFactory();
//创建磁盘文件项
ServletFileUpload fileUpload = new ServletFileUpload(fileItemFactory);
// fileUpload.setHeaderEncoding("utf-8");
fileUpload.setHeaderEncoding("UTF-8");// 解决中文文件名上传乱码.
//解析上传项
List<FileItem> list = fileUpload.parseRequest(request);
Map<String,String> map = new HashMap<String,String>();
String fileName = null;
for (FileItem fileItem : list) {
if(fileItem.isFormField()){
//如果是表单项
String name = fileItem.getFieldName();
String string = fileItem.getString("utf-8");
//表单项的集合
map.put(name, string);
}else{
//上传项
fileName = fileItem.getName();
InputStream is = fileItem.getInputStream();
// 获得文件要上传的路径(后面的路径可以自定义):
String path = this.getServletContext().getRealPath("/back/imgs");
OutputStream os = new FileOutputStream(path+"/"+fileName);//cs.jpg
byte[] byts = new byte[1024];
int len = 0;
while ( (len = is.read(byts)) != -1 ) {
os.write(byts, 0, len);
os.flush();
}
// IOUtils.copy(is, os);
is.close();
os.close();
}
}
// BeanUtils.populate(); //将实体对应的属性赋给实体(收集数据)
if (!fileName.equals(null)&&!fileName.equals("")) {
//将图片路径赋给实体的某个属性
}
//将实体的数据写入到数据库
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
注:
1. 上面的java部分的代码可以直接使用,只需要将上传的图片路径及收集数据并将数据写入到数据库即可
2. 上面上传文件使用到了字节流,其实还可以使用别的流,这个需要读者自己在下面完善测试
3. BeanUtils是一个工具 便于将实体对应的属性赋给实体
4. 上传文件不能使用 request.getParameter("")获取参数了,而是直接将request解析,通过判断每一项是文件还是非文件,然后进行相应的操作(文件的话就是用流来读取,非文件的话,暂时保存到一个map中。)