文件上传下载

需要导入两个jar包:fileupload.jar、io.jar

test.html
<form method="post" action="ImgServlet" enctype="multipart/form-data" name="uploadform">
照片:<input type="file" name="uploadfile">
<input type="submit" value="上传" class="bt">
<span class="tfont">(为商品添加图片)只能上传 *.jpg , *.gif</span>
</form>


ImgServlet

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Calendar;
import java.util.Iterator;
import java.util.List;
import java.util.Random;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.DiskFileUpload;
import org.apache.commons.fileupload.FileItem;

public class AddProImgServlet extends HttpServlet {

/**
* Constructor of the object.
*/
public AddProImgServlet() {
super();
}

/**
* Destruction of the servlet. <br>
*/
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}

/**
* The doGet method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to get.
*
* @param request
* the request send by the client to the server
* @param response
* the response send by the server to the client
* @throws ServletException
* if an error occurred
* @throws IOException
* if an error occurred
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

response.setContentType("text/html");
PrintWriter out = response.getWriter();
String imageUrl = null;
// 图片上传路径
String uploadPath = request.getRealPath("/") + "products/";
// 图下临时上传路径
String tempPath = request.getRealPath("/") + "products/temp/";
// 数据库中图片网络相对路径
String imagePath = request.getScheme() + "://"
+ request.getServerName() + ":" + request.getServerPort()
+ request.getContextPath() + "/";
// 数据库中图片网络URL
// 文件夹不存在就自动创建:
if (!new File(uploadPath).isDirectory())
new File(uploadPath).mkdirs();
if (!new File(tempPath).isDirectory())
new File(tempPath).mkdirs();
try {
DiskFileUpload fu = new DiskFileUpload();
// 设置最大文件尺寸,这里是4MB
fu.setSizeMax(4194304);
// 设置缓冲区大小,这里是4kb
fu.setSizeThreshold(4096);
// 设置临时目录:
fu.setRepositoryPath(tempPath);

// 得到所有的文件:

List fileItems = fu.parseRequest(request);
Iterator i = fileItems.iterator();
// 依次处理每一个文件:
while (i.hasNext()) {
FileItem file = (FileItem) i.next();
// 获得文件名,这个文件名是用户上传时用户的绝对路径:
String fileName = file.getName();
// 看文件以什么结束
// System.out.println(fileName.endsWith(".gif"));

if (fileName != null
&& (fileName.endsWith(".jpg")
|| fileName.endsWith(".gif") || fileName
.endsWith(".doc"))) {
// 在这里可以记录用户和文件信息
// 生成上传后的文件名
String filename = null;
Random rd = new Random();
Calendar time = Calendar.getInstance();
if (fileName.endsWith(".jpg")) {
filename = String.valueOf(time.get(Calendar.YEAR))
+ String.valueOf(time.get(Calendar.MONTH))
+ String.valueOf(time
.get(Calendar.DAY_OF_MONTH))
+ String
.valueOf(time.get(Calendar.HOUR_OF_DAY))
+ String.valueOf(time.get(Calendar.MINUTE))
+ String.valueOf(time.get(Calendar.SECOND))
+ String.valueOf(rd.nextInt(100)) + ".jpg";
} else if (fileName.endsWith(".gif")) {
filename = String.valueOf(time.get(Calendar.YEAR))
+ String.valueOf(time.get(Calendar.MONTH))
+ String.valueOf(time
.get(Calendar.DAY_OF_MONTH))
+ String
.valueOf(time.get(Calendar.HOUR_OF_DAY))
+ String.valueOf(time.get(Calendar.MINUTE))
+ String.valueOf(time.get(Calendar.SECOND))
+ String.valueOf(rd.nextInt(100)) + ".gif";
}
File f1 = new File(uploadPath + filename);
// 打印相对路径
// System.out.print(f1.getAbsolutePath());
// 数据库中存储图片路径为:
// http://127.0.0.1:8080/MailSend/upload/images/1.jpg
// 要写入数据库的路径 imageUrl
file.write(f1);
imageUrl = imagePath + "products/" + filename;

if(flag){
//成功后跳转到主面
response.sendRedirect("index.jsp");
}
else {
response.sendRedirect("error.jsp"); //失败后跳转到错误页
}
}
}
// 跳转到上传成功提示页面
} catch (Exception e) {
// 可以跳转出错页面
}
out.flush();
out.close();

}

/**
* The doPost method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to
* post.
*
* @param request
* the request send by the client to the server
* @param response
* the response send by the server to the client
* @throws ServletException
* if an error occurred
* @throws IOException
* if an error occurred
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

this.doGet(request, response);
}

/**
* Initialization of the servlet. <br>
*
* @throws ServletException
* if an error occure
*/
public void init() throws ServletException {
// Put your code here
}

}
1、资源项目源码均已通过严格测试验证,保证能够正常运行; 2、项目问题、技术讨论,可以给博主私信或留言,博主看到后会第一时间与您进行沟通; 3、本项目比较适合计算机领域相关的毕业设计课题、课程作业等使用,尤其对于人工智能、计算机科学与技术等相关专业,更为适合; 、4下载使用后,可先查看README.md或论文文件(如有),本项目仅用作交流学习参考,请切勿用于商业用途。 5、资源来自互联网采集,如有侵权,私聊博主删除。 6、可私信博主看论文后选择购买源代码。 1、资源项目源码均已通过严格测试验证,保证能够正常运行; 2、项目问题、技术讨论,可以给博主私信或留言,博主看到后会第一时间与您进行沟通; 3、本项目比较适合计算机领域相关的毕业设计课题、课程作业等使用,尤其对于人工智能、计算机科学与技术等相关专业,更为适合;、下载 4使用后,可先查看README.md或论文文件(如有),本项目仅用作交流学习参考,请切勿用于商业用途。 5、资源来自互联网采集,如有侵权,私聊博主删除。 6、可私信博主看论文后选择购买源代码。 1、资源项目源码均已通过严格测试验证,保证能够正常运行; 2、项目问题、技术讨论,可以给博主私信或留言,博主看到后会第一时间与您进行沟通; 3、本项目比较适合计算机领域相关的毕业设计课题、课程作业等使用,尤其对于人工智能、计算机科学与技术等相关专业,更为适合;、 4下载使用后,可先查看README.md或论文文件(如有),本项目仅用作交流学习参考,请切勿用于商业用途。 5、资源来自互联网采集,如有侵权,私聊博主删除。 6、可私信博主看论文后选择购买源代码。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值