本文整理汇总了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;
}
}