直播网站源码,上传图片到项目目录并将相对路径保存到数据库
直播网站源码,上传图片到项目目录并将相对路径保存到数据库
HTML
<form action="${pageContext.request.contextPath}/pictureServlet" method="post" enctype="multipart/form-data">
<input id="input" type="file" name="file">
<button id="btn" type="submit ">提交</button>
</form>
<img id="img" src="">
JS实现预览
此时的预览所获得的路径不能传到后台操作,是blob:http…格式,下面会说
$("#a").change(function (e) {
console.log(e)
reader.readAsDataURL(this.files[0]);
reader.onload = function(e){
console.log(e.target.result);
document.getElementById("img").src = e.target.result;
}
})
Servlet
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import javax.net.ssl.HttpsURLConnection;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
@WebServlet("/pictureServlet")
public class PictureServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setContentType("text/plain;charset=utf-8");
//此处将新建的文件直接保存到项目的绝对路径中。File没有读写能力。
File savePath = new File("E:\\javaEE\\Project\\Picture\\web\\images");
DiskFileItemFactory factory = new DiskFileItemFactory();//jar包的类
ServletFileUpload upload = new ServletFileUpload(factory);//jar包的类
try {
List<FileItem> items = upload.parseRequest(request);
//将前端的表单数据封装成list。
//form表单必须加enctype="multipart/form-data",在使用包含文件上传控件的表单时,必须使用该值。
for (FileItem item:items){
if(item.isFormField()){
//说明普通表单项
}else {
//说明上传文件项
//获取上传文件的名称
String name = item.getName();
//获取相对路径
String path = request.getContextPath()+"/images/"+name;
//将相对路径保存到数据库
Test test = new Test();
test.update(path);
//使用绝对路径完成文件上传
item.write(new File(savePath,name));
//删除临时文件
item.delete();
}
}
} catch (FileUploadException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request,response);
}
}
以上就是直播网站源码,上传图片到项目目录并将相对路径保存到数据库, 更多内容欢迎关注之后的文章