Java上传图片方法

2017-04-23 20:45 阅读 1,103 次 评论 0 条
  1. 导入类库

  1. 编写Servlet

package com.langsin.servlet;

import java.io.File;

import java.io.IOException;

import java.io.PrintWriter;

import java.util.Iterator;

import java.util.List;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

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;

 

public class Upload extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

doGet(request, response);

}

public void doPost(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

response.setContentType("text/html;charset=utf-8");

PrintWriter out = response.getWriter();

//获取保存上传文件的目录

String uploadDir = getServletContext().getRealPath("/upload");

if (uploadDir == null) {

out.println("无法访问存储目录!");

return;

}

File fUploadDir = new File(uploadDir);

if (!fUploadDir.exists()) {

if (!fUploadDir.mkdir()) {

out.println("无法创建存储目录!");

return;

}

}

if(!ServletFileUpload.isMultipartContent(request)){

out.println("只能处理multipart/form-data类型的数据!");

return;

}

DiskFileItemFactory factory = new DiskFileItemFactory();

// 超过1M的字段数据采用临时文件缓存

factory.setSizeThreshold(1024*1024);

factory.setRepository(fUploadDir);

ServletFileUpload fu = new ServletFileUpload(factory);

// 最多上传200M数据

fu.setSizeMax(1024*1024*200);

// 设置上传的普通字段的名称和文件字段的文件名所采用的字符集编码

fu.setHeaderEncoding("utf-8");

// 得到所有表单字段对象的集合

List fileItems = null;

try {

fileItems = fu.parseRequest(request);

} catch (FileUploadException e) {

out.println("解析数据时出现如下问题:");

e.printStackTrace(out);

return;

}

// 处理每个表单字段

Iterator i = fileItems.iterator();

while (i.hasNext()) {

FileItem fi = (FileItem) i.next();

if (fi.isFormField()) {

String content = fi.getString("UTF-8");

String fieldName = fi.getFieldName();

request.setAttribute(fieldName, content);

} else {

try {

String pathSrc = fi.getName();

/*

* 如果用户没有在FORM表单的文件字段中选择任何文件, 那么忽略对该字段项的处理

*/

if (pathSrc.trim().equals("")) {

continue;

}

int start = pathSrc.lastIndexOf('\\');

String fileName = pathSrc.substring(start + 1);

File pathDest = new File(uploadDir, fileName);

 

fi.write(pathDest);

String fieldName = fi.getFieldName();

request.setAttribute(fieldName, fileName);

} catch (Exception e) {

out.println("存储文件时出现如下问题:");

e.printStackTrace(out);

return;

} finally // 总是立即删除保存表单字段内容的临时文件

{

fi.delete();

}

}

}

String author = (String) request.getAttribute("author");

System.out.println(author);

// 显示处理结果

out.println("用户:" + request.getAttribute("author") + "<br>");

out.println("来自:" + request.getAttribute("company") + "<br>");

/*

* 将上传的文件名组合成"file1,file2"这种形式显示出来,如果没有上传

* 任何文件,则显示为"无",如果只上传了第二个文件,显示为"file2"。

*/

StringBuffer filelist = new StringBuffer();

String file1 = (String) request.getAttribute("file1");

makeUpList(filelist, file1);

String file2 = (String) request.getAttribute("file2");

makeUpList(filelist, file2);

out.println("成功上传的文件:"

+ (filelist.length() == 0 ? "无" : filelist.toString()));

}

/**

*将一段字符串追加到一个结果字符串中。如果结果字符串的初始内容不为空, 在追加当前这段字符串之前先最加一个逗号(,)。在组合sql语句的查询条件时,

* 经常要用到类似的方法,第一条件前没有"and",而后面的条件前都需要用"and"

* 作连词,如果没有选择第一个条件,第二个条件就变成第一个,依此类推。

*

*@param result

*            要将当前字符串追加进去的结果字符串

*@param fragment

*            当前要追加的字符串

*/

private void makeUpList(StringBuffer result, String fragment) {

if (fragment != null) {

if (result.length() != 0) {

result.append(",");

}

result.append(fragment);

}

}

}

  1. 编写jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>

<html>

<head>

<title>upload experiment</title>

</head>

<body>

<h3>测试文件上传组件的页面</h3>

<form action="up"

enctype="multipart/form-data" method="post">

作者:<input type="text" name="author"><br>

来自:<input type="text" name="company"><br>

文件1:<input type="file" name="file1"><br>

文件2:<input type="file" name="file2"><br>

<input type="submit" value="上载">

</form>

</body>

</html>

版权声明:本文著作权归原作者所有,欢迎分享本文,谢谢支持!
转载请注明:Java上传图片方法 | 猿笔记
分类:JAVA, 程序笔记 标签:,

发表评论


表情