Image 如何使用servlet将图像上载到绝对路径
我想上传一个文件到我的项目文件夹。我的代码如下:Image 如何使用servlet将图像上载到绝对路径,image,jsp,servlets,apache-commons,Image,Jsp,Servlets,Apache Commons,我想上传一个文件到我的项目文件夹。我的代码如下: protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { File savedFile; String destination; List<FileItem> items = null; try { item
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
File savedFile;
String destination;
List<FileItem> items = null;
try {
items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
} catch (FileUploadException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for (FileItem item : items) {
if (item.isFormField()) {
// Process regular form field (input type="text|radio|checkbox|etc", select, etc).
} else {
// Process form file field (input type="file").
String fieldName = item.getFieldName();
String fileName = FilenameUtils.getName(item.getName());
InputStream fileContent = item.getInputStream();
String userName = (String) session.getAttribute("newUser");
destination = getServletConfig().getServletContext().getContextPath() + "\\" + userName + ".jpeg";
savedFile = new File(destination);
//Check if file exists
if(!savedFile.exists())
savedFile.createNewFile();
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(savedFile));
byte[] buffer = new byte[1024];
int len;
//Read from file and write to new file destination
while((len = fileContent.read(buffer)) >= 0) {
bos.write(buffer, 0, len);
}
//Closing the streams
fileContent.close();
bos.close();
}
}
}
protectedvoiddopost(HttpServletRequest请求,HttpServletResponse响应)抛出ServletException,IOException{
文件保存文件;
字符串目的地;
列表项=空;
试一试{
items=new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
}捕获(文件上载异常){
//TODO自动生成的捕捉块
e、 printStackTrace();
}
用于(文件项:项){
if(item.isFormField()){
//处理常规表单字段(输入type=“text | radio | checkbox | etc”,选择等)。
}否则{
//处理表单文件字段(输入类型=“文件”)。
字符串fieldName=item.getFieldName();
字符串fileName=FilenameUtils.getName(item.getName());
InputStream fileContent=item.getInputStream();
字符串用户名=(字符串)session.getAttribute(“newUser”);
destination=getServletConfig().getServletContext().getContextPath()+“\\”+用户名+“.jpeg”;
savedFile=新文件(目标);
//检查文件是否存在
如果(!savedFile.exists())
savedFile.createNewFile();
BufferedOutputStream bos=新的BufferedOutputStream(新文件输出流(savedFile));
字节[]缓冲区=新字节[1024];
内伦;
//从文件读取并写入新文件目标
而((len=fileContent.read(buffer))>=0){
写入(缓冲区,0,len);
}
//关闭溪流
fileContent.close();
bos.close();
}
}
}
当我运行jsp文件,浏览并选择所需的图像并提交表单时,servlet运行,但抛出IOException。异常由我使用savedFile.createNewFile()创建新路径的行引发。在我使用该代码之前,它抛出了另一个FileNotFoundException。我不确定我提供的路径是否正确。尝试使用
getRealPath()
方法
String fileName="/" + userName + ".jpeg";
destination = getServletContext().getRealPath(fileName);
savedFile = new File(destination);
userName是我从会话对象访问的字符串值,该对象返回null。它的值在另一个servlet中设置,但我不确定它为什么返回null。这可能是编码类型的影响吗?但是会话对象应该在整个会话中仍然可用。不是吗?