使用smartupload上传图片

java

package com.ljr.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
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.lxh.smart.File;
import org.lxh.smart.SmartUpload;
import org.lxh.smart.SmartUploadException;

public class UploadServlet extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		doPost(request, response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		request.setCharacterEncoding("utf-8");
		try {
		 	SmartUpload su = new SmartUpload();
		 	
	       su.initialize(this.getServletConfig(),request,response);
	       su.setMaxFileSize(1024*1024);
	       su.setTotalMaxFileSize(9*1024*1024);
	       
	       su.upload();
	       
		       int count=0;
		       for(int i=0;i<su.getFiles().getCount();i++){
		         File file = su.getFiles().getFile(i);
		          if(file.isMissing()){
		            continue;
		       }
		      //重命名文件名
		       count++;
		       DateFormat dtf = new SimpleDateFormat("yyyyMMddHHmmss");
		       String date = dtf.format(new Date());
		       Random random = new Random();
		       String rand = "";
		       for(int j=0;j<3;j++){
		           rand = rand+random.nextInt(10)+"";
		       }
		       
		       String fileSaveName = date + rand+i;
		       System.out.println(fileSaveName);
		       //存储路径(upload为项目中已经创建的文件夹)
		       file.saveAs("/upload/"+fileSaveName+"."+file.getFileExt());
		       //存储的路径(存入数据库的url)
		       String url = "upload/"+fileSaveName+"."+file.getFileExt();
		       System.out.println(url);
		       request.getRequestDispatcher("./index.jsp").forward(request, response);
		       }
		} catch (SmartUploadException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		out.flush();
		out.close();
	}

}
jsp页面

<form action="uploadServlet" method="post" enctype="multipart/form-data">
  <input type="file" id="file" name="file"/><input type="submit" value="上传">
 </form>



评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值