1. 程式人生 > >FileUpLoad 做圖片上傳

FileUpLoad 做圖片上傳

package upload;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
public class upload {
public void inputFile(HttpServletRequest request, HttpServletResponse response) throws IOException{
request.setCharacterEncoding(“utf-8”);
//獲得磁碟檔案條目工廠。
DiskFileItemFactory factory=new DiskFileItemFactory();
//獲取檔案上傳需要儲存的路徑,upload資料夾需存在。
String path = request.getSession().getServletContext().getRealPath(“/”);
path=path.substring(0, path.indexOf(“\”, path.indexOf(“\”, path.indexOf(“\”, 0)+1)+1)+1)+”manager\images”;
//設定暫時存放檔案的儲存室
factory.setRepository(new File(path));
//設定快取的大小
factory.setSizeThreshold(1024*1024);
//上傳處理工具類
ServletFileUpload upload = new ServletFileUpload(factory);
//設定上傳單個檔案的大小的最大值
upload.setFileSizeMax(1024*1024*10);
//設定上傳檔案總量的最大值
upload.setSizeMax(1024*1024*30);
upload.setHeaderEncoding(“UTF-8”);
try{
//呼叫 parseRequest(request)方法 獲得上傳檔案 FileItem 的集合list 可實現多檔案上傳。
List list =(List)upload.parseRequest(request);
for(FileItem item:list){
//獲取表單屬性名字。
String sth = item.getFieldName();
//此處是安卓端返回的圖片名稱以及其他引數我用////截出待用
String[] items =sth.split(“////”);
String name=items[0].toString();
String ID=null;
if(items.length==2){
ID=items[1].toString();
}
//取到最後一個反斜槓。
int start = name.lastIndexOf(“\”);
//擷取上傳檔案的 字串名字。+1是去掉反斜槓。
String filename = name.substring(start+1);
request.setAttribute(name, filename);
//第三方提供的方法直接寫到檔案中。
item.write(new File(path,filename));
//收到寫到接收的檔案中。
OutputStream out = new FileOutputStream(new File(path,filename));
InputStream in = item.getInputStream();
int length = 0;
byte[] buf = new byte[1024];
while((length = in.read(buf))!=-1){
out.write(buf,0,length);
}
in.close();
out.close();
//獲取當前伺服器的IP地址
InetAddress address = InetAddress.getLocalHost();
String ip=address.getHostAddress();
String url=ip+”:8080\”+”manager\images\”+filename;
}
}catch(Exception e){
e.printStackTrace();
}
}
}
小結:
1.需要commons-fileupload-1.3.1.jar包
2.檔案從request中傳入的二進位制流,通過ServletFileUpload 的parseRequest 方法讀取出檔案集合(此處指檔案集合也就是可以同時傳入多個檔案)
3.如果request裡傳入的檔案是存在的但是items裡面是空的,那可能是xml裡面配置有了問題。