JAVA 关于图片上传的代码
private File file; private String fileFileName; private String picture; //都有getter 和 setter InputStream is = new FileInputStream(file); //引入一个IO流的输入流String root = ServletActionContext.getRequest() .getRealPath("/bookpicture"); //通过REQUEST来得到相对地址,并在后面加上/bookpictureFile f = new File(root, this.getFileFileName()); //定义一个FILE文件,第一个参数是文件的路径,第二个是文件的名字picture="."+"\\"+"bookpicture"+"\\"+this.getFileFileName();//为PICTURE字符串赋值,/地址/文件名 System.out.println ("======picture====="+picture); //从控制台输出PictureOutputStream os = new FileOutputStream(f); //第一个文件的输出流byte[] buffer = new byte[1024];//定义一个bufer的字符串,长度为1024 int len = 0; while ((len = is.read(buffer)) > 0) { //如果从制定文件中读取到的信息为结束就继续循环os.write(buffer, 0, len); //将文件读出的内容写入到指定的文件中}
package com;import java.io.*;import javax.servlet.*;import javax.servlet.http.*;import javax.servlet.jsp.*;import com.jspsmart.upload.*;public class uploadfiles extends HttpServlet{public void doGet(HttpServletRequest request,HttpServletResponse response)throws ServletException,IOException{//使用了一个第三方的组件,存放在web-inf/lib下 response.setContentType("text/html;charset=GB2312"); //由于SmartUpload的初始化方法需要pageContext,所以我们在servlet中得到他 //为了得到pageConext要首先得到JspFactory的实例 //通过JspFactory的实例的getPageContext方法得到pageConext的实例JspFactory jf = null;//得到JspFactory的实例jf=JspFactory.getDefaultFactory();/*getPageContext(Servlet servlet, ServletRequest request, ServletResponse response, java.lang.String errorPageURL, boolean needsSession, int buffer, boolean autoflush) */ PageContext pageContext=jf.getPageContext(this,request,response,null,true,8192,true);try{//实例化SmartUploadSmartUpload mySmartUpload=new SmartUpload();//初始化SmartUpload的实例,需要PageContext的实例mySmartUpload.initialize(pageContext);//设定最大上传的字节数,其实可以不进行设定,表示上传的文件没有大小限制//mySmartUpload.setTotalMaxFileSize(10000000);mySmartUpload.upload();//下面是单文件上传//上传的文件以com.jspsmart.upload.File 代表,如果文件名称重复,则进行覆盖com.jspsmart.upload.File file=mySmartUpload.getFiles().getFile(0);String upLoadFileName=file.getFileName();//调用com.jspsmart.upload.File实例的saveas的方法保存文件,此时的文件名即是//保存到服务器上的文件名file.saveAs("/upload/"+upLoadFileName);Request req = Text t = .....;t.setUpload(upLoadFileName);t.set.....(req);}catch(SmartUploadException e){System.out.println(e.getMessage());}}protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, java.io.IOException{doGet(request,response);}}