本文整理匯總了Java中org.apache.commons.fileupload.servlet.ServletFileUpload.setHeaderEncoding方法的典型用法代碼示例。如果您正苦於以下問題:Java ServletFileUpload.setHeaderEncoding方法的具體用法?Java ServletFileUpload.setHeaderEncoding怎麽用?Java ServletFileUpload.setHeaderEncoding使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類org.apache.commons.fileupload.servlet.ServletFileUpload
的用法示例。
在下文中一共展示了ServletFileUpload.setHeaderEncoding方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。
示例1: parseRequestMultiPartItems
import org.apache.commons.fileupload.servlet.ServletFileUpload; //導入方法依賴的package包/類
/**
* Gets the FileItemIterator of the input.
*
* Can be used to process uploads in a streaming fashion. Check out:
* http://commons.apache.org/fileupload/streaming.html
*
* @return the FileItemIterator of the request or null if there was an
* error.
*/
public Optional<List<FormItem>> parseRequestMultiPartItems(String encoding) {
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold(properties.getInt(Constants.PROPERTY_UPLOADS_MAX_SIZE/*Constants.Params.maxUploadSize.name()*/));//Configuration.getMaxUploadSize());
factory.setRepository(new File(System.getProperty("java.io.tmpdir"))); //Configuration.getTmpDir());
//README the file for tmpdir *MIGHT* need to go into Properties
ServletFileUpload upload = new ServletFileUpload(factory);
if(encoding != null)
upload.setHeaderEncoding(encoding);
upload.setFileSizeMax(properties.getInt(Constants.PROPERTY_UPLOADS_MAX_SIZE));
try {
List<FormItem> items = upload.parseRequest(request)
.stream()
.map(item -> new ApacheFileItemFormItem(item))
.collect(Collectors.toList());
return Optional.of(items);
} catch (FileUploadException e) {
//"Error while trying to process mulitpart file upload"
//README: perhaps some logging
}
return Optional.empty();
}
示例2: doGet
import org.apache.commons.fileupload.servlet.ServletFileUpload; //導入方法依賴的package包/類
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
try
{
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setHeaderEncoding("UTF-8");
if (!ServletFileUpload.isMultipartContent(request))
{
return;
}
this.fileList = upload.parseRequest(request);
// System.out.println(fileList.size());
for (FileItem item : fileList)
{
if (item.isFormField())
{
String value = item.getString("UTF-8");
// System.out.print(value);
names.add(value);
} else
{
String filename = item.getName();
if (filename == null) continue;
File newFile = new File(filename);
// System.out.println(newFile.getCanonicalPath());
// item.write(newFile);
this.names.add(newFile.getAbsolutePath().toString());
saveFile(item);
}
}
} catch (Exception e)
{
e.printStackTrace();
}
}
示例3: initFields
import org.apache.commons.fileupload.servlet.ServletFileUpload; //導入方法依賴的package包/類
/**
* 處理上傳內容
*
* @param request
* @param maxSize
* @return
*/
// @SuppressWarnings("unchecked")
private Map<String, Object> initFields(HttpServletRequest request) {
// 存儲表單字段和非表單字段
Map<String, Object> map = new HashMap<String, Object>();
// 第一步:判斷request
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
// 第二步:解析request
if (isMultipart) {
// Create a factory for disk-based file items
DiskFileItemFactory factory = new DiskFileItemFactory();
// 閥值,超過這個值才會寫到臨時目錄,否則在內存中
factory.setSizeThreshold(1024 * 1024 * 10);
factory.setRepository(new File(tempPath));
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setHeaderEncoding("UTF-8");
// 最大上傳限製
upload.setSizeMax(maxSize);
/* FileItem */
List<FileItem> items = null;
// Parse the request
try {
items = upload.parseRequest(request);
} catch (FileUploadException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// 第3步:處理uploaded items
if (items != null && items.size() > 0) {
Iterator<FileItem> iter = items.iterator();
// 文件域對象
List<FileItem> list = new ArrayList<FileItem>();
// 表單字段
Map<String, String> fields = new HashMap<String, String>();
while (iter.hasNext()) {
FileItem item = iter.next();
// 處理所有表單元素和文件域表單元素
if (item.isFormField()) { // 表單元素
String name = item.getFieldName();
String value = item.getString();
fields.put(name, value);
} else { // 文件域表單元素
list.add(item);
}
}
map.put(FORM_FIELDS, fields);
map.put(FILE_FIELDS, list);
}
}
return map;
}
示例4: getParameterMapForMultipart
import org.apache.commons.fileupload.servlet.ServletFileUpload; //導入方法依賴的package包/類
/**
* File Uploadがある場合のパラメータ解析を行います。
* @param req HTTPリクエスト。
* @return パラメータ解析結果。
* @throws Exception 例外。
*/
private Map<String, Object> getParameterMapForMultipart(final HttpServletRequest req) throws Exception {
Map<String, Object> map = new HashMap<String, Object>();
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setRepository(new File(tempDir)); //一時的に保存する際のディレクトリ
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setHeaderEncoding(encoding);
@SuppressWarnings("unchecked")
List<FileItem> list = upload.parseRequest(req);
for (FileItem item : list) {
String key = item.getFieldName();
if (key != null) {
if (item.isFormField()) {
String value = item.getString(encoding);
this.addParamMap(map, key, value);
} else {
String filename = item.getName();
if (StringUtil.isBlank(filename)) {
map.put(key, null);
} else {
map.put(key, item);
}
}
}
}
return map;
}
示例5: getFileUploadComponent
import org.apache.commons.fileupload.servlet.ServletFileUpload; //導入方法依賴的package包/類
private ServletFileUpload getFileUploadComponent()
{
DiskFileItemFactory dif=new DiskFileItemFactory();
if(factorySizeThreshold!=DEFAULT_SIZE_THRESHOLD)
{
dif.setSizeThreshold(factorySizeThreshold);
}
if(factoryRepository!=null)
{
dif.setRepository(new File(factoryRepository));
}
if(factoryCleaningTracker!=null)
{
dif.setFileCleaningTracker(factoryCleaningTracker);
}
ServletFileUpload sfu=new ServletFileUpload(dif);
if(sizeMax!=NO_LIMIT_SIZE_MAX)
{
sfu.setSizeMax(sizeMax);
}
if(fileSizeMax!=NO_LIMIT_FILE_SIZE_MAX)
{
sfu.setFileSizeMax(fileSizeMax);
}
if(servletHeaderencoding!=null)
{
sfu.setHeaderEncoding(servletHeaderencoding);
}
if(servletProgressListener!=null)
{
sfu.setProgressListener(servletProgressListener);
}
return sfu;
}
示例6: init
import org.apache.commons.fileupload.servlet.ServletFileUpload; //導入方法依賴的package包/類
/**
* Init Method
* @param servletContext
*/
public static void init(ServletContext servletContext){
// Create a factory for disk-based file items
DiskFileItemFactory factory = new DiskFileItemFactory();
// Configure a repository (to ensure a secure temp location is used)
File repository = (File) servletContext.getAttribute("javax.servlet.context.tempdir");
factory.setRepository(repository);
fileUpload = new ServletFileUpload(factory);
long fileMaxSize = Express4JConfig.getMaxFileSize();
fileUpload.setFileSizeMax(fileMaxSize);
fileUpload.setHeaderEncoding(DEFAULT_FIELD_ENCODING);
}
示例7: createServletFileUpload
import org.apache.commons.fileupload.servlet.ServletFileUpload; //導入方法依賴的package包/類
protected ServletFileUpload createServletFileUpload(HttpServletRequest request) {
final DiskFileItemFactory fileItemFactory = createDiskFileItemFactory();
final ServletFileUpload upload = newServletFileUpload(fileItemFactory);
upload.setHeaderEncoding(request.getCharacterEncoding());
upload.setSizeMax(getSizeMax());
return upload;
}
示例8: doPost
import org.apache.commons.fileupload.servlet.ServletFileUpload; //導入方法依賴的package包/類
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// �ж��ϴ����Ƿ�����ļ�
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if (isMultipart) {
// ��ȡ·��
String realpath = request.getSession().getServletContext().getRealPath("/files");
System.out.println(realpath);
File dir = new File(realpath);
if (!dir.exists())
dir.mkdirs();
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setHeaderEncoding("UTF-8");
try {
// ����������� ��ʵ���� form����ÿ��input�ڵ�
List<FileItem> items = upload.parseRequest(request);
for (FileItem item : items) {
if (item.isFormField()) {
// ����DZ� ����ÿ���� ��ӡ������̨
String name1 = item.getFieldName();// �õ��������������
String value = item.getString("UTF-8");// �õ�����ֵ
System.out.println(name1 + "=" + value);
} else {
// ���ļ�д����ǰservlet����Ӧ��·��
item.write(new File(dir, System.currentTimeMillis()
+ item.getName().substring(item.getName().lastIndexOf("."))));
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
示例9: doPost
import org.apache.commons.fileupload.servlet.ServletFileUpload; //導入方法依賴的package包/類
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// �ж��ϴ����Ƿ�����ļ�
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if (isMultipart) {
// ��ȡ·��
String realpath = request.getSession().getServletContext()
.getRealPath("/files");
System.out.println(realpath);
File dir = new File(realpath);
if (!dir.exists())
dir.mkdirs();
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setHeaderEncoding("UTF-8");
try {
// ����������� ��ʵ���� form����ÿ��input�ڵ�
List<FileItem> items = upload.parseRequest(request);
for (FileItem item : items) {
if (item.isFormField()) {
// ����DZ� ����ÿ���� ��ӡ������̨
String name1 = item.getFieldName();// �õ��������������
String value = item.getString("UTF-8");// �õ�����ֵ
System.out.println(name1 + "=" + value);
} else {
// ���ļ�д����ǰservlet����Ӧ��·��
item.write(new File(dir, System.currentTimeMillis()
+ item.getName().substring(
item.getName().lastIndexOf("."))));
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
示例10: createFileUpload
import org.apache.commons.fileupload.servlet.ServletFileUpload; //導入方法依賴的package包/類
private ServletFileUpload createFileUpload(String encoding) {
DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory(_sizeThreshold, _tempDir);
diskFileItemFactory.setFileCleaningTracker(_fileCleaningTracker);
ServletFileUpload fileUpload = new ServletFileUpload(diskFileItemFactory);
fileUpload.setHeaderEncoding(encoding);
fileUpload.setFileSizeMax(_fileSizeMax);
fileUpload.setSizeMax(_sizeMax);
//_fileUploadEncodingMap.put(fileUpload.getHeaderEncoding(), fileUpload);
return fileUpload;
}
示例11: asMultipartRequest
import org.apache.commons.fileupload.servlet.ServletFileUpload; //導入方法依賴的package包/類
private static MultipartRequest asMultipartRequest(HttpServletRequest request) throws Exception {
String encoding = request.getCharacterEncoding();
MultipartRequest req = new MultipartRequest(request);
ServletFileUpload upload = new ServletFileUpload();
upload.setHeaderEncoding(encoding);
FileItemIterator it = upload.getItemIterator(request);
while (it.hasNext()) {
FileItemStream item = it.next();
String fieldName = item.getFieldName();
InputStream stream = item.openStream();
try {
if (item.isFormField()) {
req.setParameter(fieldName, Streams.asString(stream, encoding));
} else {
String originalFilename = item.getName();
File diskFile = getTempFile(originalFilename);
OutputStream fos = new FileOutputStream(diskFile);
try {
IoUtils.copy(stream, fos);
} finally {
IoUtils.closeQuietly(fos);
}
FilePart filePart = new FilePart(fieldName, originalFilename, diskFile);
req.addFile(filePart);
}
} finally {
IoUtils.closeQuietly(stream);
}
}
return req;
}
示例12: initFields
import org.apache.commons.fileupload.servlet.ServletFileUpload; //導入方法依賴的package包/類
/**
* 處理上傳內容
*
* @param request
* @param maxSize
* @return
*/
// @SuppressWarnings("unchecked")
private Map<String, Object> initFields(HttpServletRequest request) {
// 存儲表單字段和非表單字段
Map<String, Object> map = new HashMap<String, Object>();
// 第一步:判斷request
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
// 第二步:解析request
if (isMultipart) {
// Create a factory for disk-based file items
DiskFileItemFactory factory = new DiskFileItemFactory();
// 閥值,超過這個值才會寫到臨時目錄,否則在內存中
factory.setSizeThreshold(1024 * 1024 * 10);
factory.setRepository(new File(tempPath));
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setHeaderEncoding("UTF-8");
// 最大上傳限製
upload.setSizeMax(maxSize);
/* FileItem */
List<FileItem> items = null;
// Parse the request
try {
items = upload.parseRequest(request);
} catch (FileUploadException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// 第3步:處理uploaded items
if (items != null && items.size() > 0) {
Iterator<FileItem> iter = items.iterator();
// 文件域對象
List<FileItem> list = new ArrayList<FileItem>();
// 表單字段
Map<String, String> fields = new HashMap<String, String>();
while (iter.hasNext()) {
FileItem item = iter.next();
// 處理所有表單元素和文件域表單元素
if (item.isFormField()) { // 表單元素
String name = item.getFieldName();
String value = item.getString();
fields.put(name, value);
} else { // 文件域表單元素
list.add(item);
}
}
map.put(FORM_FIELDS, fields);
map.put(FILE_FIELDS, list);
}
}
return map;
}
示例13: uploadFile2Folder
import org.apache.commons.fileupload.servlet.ServletFileUpload; //導入方法依賴的package包/類
/**
* 將上傳的文件放到指定的目錄下
* @param request HttpServletRequest對象
* @param sourceFolder 指定文件夾
* @param fileName 指定文件名,包含擴展名(數組)
* @return List 返回文件名集合
* @throws Exception 拋出異常
*/
public List uploadFile2Folder(HttpServletRequest request,String sourceFolder,String[] fileName)throws Exception{
DiskFileItemFactory factory = new DiskFileItemFactory();
if(sizeThreshold!=0){
factory.setSizeThreshold(sizeThreshold);
}
if(repositoryPath!=null){
factory.setRepository(new File(repositoryPath));
}
ServletFileUpload upload = new ServletFileUpload(factory);
if(sourceFolder==null){
sourceFolder="";
}
if(sizeMax!=0){
upload.setSizeMax(sizeMax);
}
if(encoding!=null){
upload.setHeaderEncoding(encoding);
}
//若指定文件加不存在,則創建
List list = new ArrayList();
File file=new File(sourceFolder);
if(!file.exists()){
file.mkdir();
}
//開始讀取上傳信息
List fileItems = upload.parseRequest(request);
if(fileItems!=null&&fileItems.size()!=0){
Iterator it=fileItems.iterator();
int i=0;
while(it.hasNext()){
FileItem fi=(FileItem)it.next();
if(!fi.isFormField()){
//忽略其他不是文檔域的任何表單信息
String name=fi.getName();
String nameDir=name;
if(name.lastIndexOf("\\")>=0){
nameDir=name.substring(name.lastIndexOf("\\"));
}
String type=null;
if(nameDir.lastIndexOf(".")>=0){
type=nameDir.substring(nameDir.lastIndexOf(".")+1);
}
//自己指定文件名
if(fileName!=null){
if(fileName[i]!=null){
nameDir=fileName[i];
}
i++;
}
//判斷是否設定了上傳的文件類型
if(type!=null&&!isHave(types,type)){
File f=new File(sourceFolder+nameDir);
fi.write(f);
list.add(sourceFolder+nameDir);
}
}
}
}
return list;
}
示例14: doGet
import org.apache.commons.fileupload.servlet.ServletFileUpload; //導入方法依賴的package包/類
/**
* 實現多文件的同時上傳
*/
public void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
System.out.println("===========");
//設置接收的編碼格式
request.setCharacterEncoding("UTF-8");
Date date = new Date();//獲取當前時間
SimpleDateFormat sdfFileName = new SimpleDateFormat("yyyyMMddHHmmss");
SimpleDateFormat sdfFolder = new SimpleDateFormat("yyMM");
// String newfileName = sdfFileName.format(date);//文件名稱
String fileRealPath = "";//文件存放真實地址
String fileRealResistPath = "";//文件存放真實相對路徑
//名稱 界麵編碼 必須 和request 保存一致..否則亂碼
String name = request.getParameter("name");
String id = request.getParameter("id"); //內容的ID,必須先添加內容,然後才能上傳圖片
// String newfileName = name;
String firstFileName="";
// 獲得容器中上傳文件夾所在的物理路徑
String savePath = this.getServletConfig().getServletContext().getRealPath("/") + "upload\\" + id +"\\";
System.out.println("路徑" + savePath+"; name:"+name);
File file = new File(savePath);
if (!file.isDirectory()) {
file.mkdirs();
}
try {
DiskFileItemFactory fac = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(fac);
upload.setHeaderEncoding("UTF-8");
// upload.setFileItemFactory(factory)
System.out.println("request:="+request);
// 獲取多個上傳文件
List fileList = fileList = upload.parseRequest(request);
System.out.println("fileList:"+fileList);
// 遍曆上傳文件寫入磁盤
Iterator it = fileList.iterator();
while (it.hasNext()) {
Object obit = it.next();
if(obit instanceof DiskFileItem){
System.out.println("xxxxxxxxxxxxx");
DiskFileItem item = (DiskFileItem) obit;
// 如果item是文件上傳表單域
// 獲得文件名及路徑
String fileName = item.getName();
if (fileName != null) {
firstFileName=item.getName().substring(item.getName().lastIndexOf("\\")+1);
String formatName = firstFileName.substring(firstFileName.lastIndexOf("."));//獲取文件後綴名
fileRealPath = savePath + fileName;//+ formatName;//文件存放真實地址
BufferedInputStream in = new BufferedInputStream(item.getInputStream());// 獲得文件輸入流
BufferedOutputStream outStream = new BufferedOutputStream(new FileOutputStream(new File(fileRealPath)));// 獲得文件輸出流
Streams.copy(in, outStream, true);// 開始把文件寫到你指定的上傳文件夾
//上傳成功,則插入數據庫
if (new File(fileRealPath).exists()) {
//虛擬路徑賦值
fileRealResistPath=sdfFolder.format(date)+"/"+fileRealPath.substring(fileRealPath.lastIndexOf("\\")+1);
//保存到數據庫
System.out.println("保存到數據庫:");
System.out.println("name:"+name);
System.out.println("虛擬路徑:"+fileRealResistPath);
}
}
}
}
} catch (org.apache.commons.fileupload.FileUploadException ex) {
ex.printStackTrace();
System.out.println("沒有上傳文件");
return;
}
response.getWriter().write("1");
}
示例15: initializeMultiPart
import org.apache.commons.fileupload.servlet.ServletFileUpload; //導入方法依賴的package包/類
private void initializeMultiPart(PageContext pc, boolean scriptProteced) {
// get temp directory
Resource tempDir = ((ConfigImpl)pc.getConfig()).getTempDirectory();
Resource tempFile;
// Create a new file upload handler
final String encoding=getEncoding();
FileItemFactory factory = tempDir instanceof File?
new DiskFileItemFactory(DiskFileItemFactory.DEFAULT_SIZE_THRESHOLD,(File)tempDir):
new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setHeaderEncoding(encoding);
//ServletRequestContext c = new ServletRequestContext(pc.getHttpServletRequest());
HttpServletRequest req = pc.getHttpServletRequest();
ServletRequestContext context = new ServletRequestContext(req) {
public String getCharacterEncoding() {
return encoding;
}
};
// Parse the request
try {
FileItemIterator iter = upload.getItemIterator(context);
//byte[] value;
InputStream is;
ArrayList<URLItem> list=new ArrayList<URLItem>();
String fileName;
while (iter.hasNext()) {
FileItemStream item = iter.next();
is=IOUtil.toBufferedInputStream(item.openStream());
if (item.getContentType()==null || StringUtil.isEmpty(item.getName())) {
list.add(new URLItem(item.getFieldName(),new String(IOUtil.toBytes(is),encoding),false));
}
else {
fileName=getFileName();
tempFile=tempDir.getRealResource(fileName);
_fileItems.put(fileName,
new Item(tempFile,item.getContentType(),item.getName(),item.getFieldName()));
String value=tempFile.toString();
IOUtil.copy(is, tempFile,true);
list.add(new URLItem(item.getFieldName(),value,false));
}
}
raw= list.toArray(new URLItem[list.size()]);
fillDecoded(raw,encoding,scriptProteced,pc.getApplicationContext().getSameFieldAsArray(SCOPE_FORM));
}
catch (Exception e) {
//throw new PageRuntimeException(Caster.toPageException(e));
fillDecodedEL(new URLItem[0],encoding,scriptProteced,pc.getApplicationContext().getSameFieldAsArray(SCOPE_FORM));
initException=e;
}
}