本文整理汇总了Java中org.apache.commons.fileupload.FileItemStream.getFieldName方法的典型用法代码示例。如果您正苦于以下问题:Java FileItemStream.getFieldName方法的具体用法?Java FileItemStream.getFieldName怎么用?Java FileItemStream.getFieldName使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类org.apache.commons.fileupload.FileItemStream
的用法示例。
在下文中一共展示了FileItemStream.getFieldName方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: processFileItemStreamAsFormField
import org.apache.commons.fileupload.FileItemStream; //导入方法依赖的package包/类
/**
* Processes the FileItemStream as a Form Field.
*
* @param itemStream file item stream
*/
private void processFileItemStreamAsFormField(FileItemStream itemStream) {
String fieldName = itemStream.getFieldName();
try {
List<String> values;
String fieldValue = Streams.asString(itemStream.openStream());
if (!parameters.containsKey(fieldName)) {
values = new ArrayList<>();
parameters.put(fieldName, values);
} else {
values = parameters.get(fieldName);
}
values.add(fieldValue);
} catch (IOException e) {
LOG.warn("Failed to handle form field '{}'.", fieldName, e);
}
}
示例2: createFileInfoFromItemStream
import org.apache.commons.fileupload.FileItemStream; //导入方法依赖的package包/类
/**
* Creates an internal <code>FileInfo</code> structure used to pass information
* to the <code>FileUploadInterceptor</code> during the interceptor stack
* invocation process.
*
* @param itemStream file item stream
* @param file the file
*/
private void createFileInfoFromItemStream(FileItemStream itemStream, File file) {
// gather attributes from file upload stream.
String fileName = itemStream.getName();
String fieldName = itemStream.getFieldName();
// create internal structure
FileInfo fileInfo = new FileInfo(file, itemStream.getContentType(), fileName);
// append or create new entry.
if (!fileInfos.containsKey(fieldName)) {
List<FileInfo> infos = new ArrayList<>();
infos.add(fileInfo);
fileInfos.put(fieldName, infos);
} else {
fileInfos.get(fieldName).add(fileInfo);
}
}
示例3: handleMultipart
import org.apache.commons.fileupload.FileItemStream; //导入方法依赖的package包/类
private String handleMultipart(RecordedRequest request) {
RecordedUpload upload = new RecordedUpload(request);
Exception exception;
try {
Map<String,String> params = new HashMap<>();
FileItemIterator iter = upload.getItemIterator();
while (iter.hasNext()) {
FileItemStream item = iter.next();
String name = item.getFieldName();
InputStream stream = item.openStream();
if (item.isFormField()) {
String value = Streams.asString(stream);
System.out.println("Form field " + name + " with value "
+ value + " detected.");
params.put(name,value);
} else {
System.out.println("File field " + name + " with file name "
+ item.getName() + " detected.");
params.put(name, "file->"+item.getName());
}
}
return "Multipart:"+JSON.toJSONString(params);
} catch (Exception e) {
exception = e;
}
return "Multipart:error->"+exception;
}
示例4: readFormData
import org.apache.commons.fileupload.FileItemStream; //导入方法依赖的package包/类
/**
* Reads form values from the multipart request until a file is encountered. Field values are stored as strings for
* retrieval using {@link #getFormFieldValue}.
* @return True if there is an upload file available to read via {@link #getUploadFileItem()}.
*/
public boolean readFormData() {
mUploadFileItem = null;
try {
while (mItemIterator.hasNext()) {
FileItemStream lCurrentItem = mItemIterator.next();
/**
* NOTE: the InputStream here is read here in a blocking way. Long upload hangs have been observed on live
* environments at this point due to network issues. It should be possible to convert the stream to a
* non-blocking stream at this point if required.
*/
InputStream lItemInputStream = lCurrentItem.openStream();
if (lCurrentItem.isFormField()) {
//Read form values into the map
String lParamName = lCurrentItem.getFieldName();
String lFieldValue = Streams.asString(lItemInputStream);
mFieldParamMap.put(lParamName, lFieldValue);
}
else {
//We've hit the file field, so stop the read for now
mUploadFileItem = lCurrentItem;
break;
}
lItemInputStream.close();
}
}
catch (IOException | FileUploadException e) {
throw new ExInternal("Failed to read form data for the multipart request", e);
}
return mUploadFileItem != null;
}
示例5: getFileItem
import org.apache.commons.fileupload.FileItemStream; //导入方法依赖的package包/类
private void getFileItem(HttpServletRequest request) throws FileUploadException, IOException {
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if (!isMultipart) {
throw new IllegalArgumentException("Not multipart...");
}
ServletFileUpload upload = new ServletFileUpload();
List<String> mdrEntries = new ArrayList<String>();
// Parse the request
FileItemIterator iter = upload.getItemIterator(request);
while (iter.hasNext()) {
FileItemStream item = iter.next();
String name = item.getFieldName();
InputStream stream = item.openStream();
if (item.isFormField()) {
System.out.println("Form field " + name + " with value "
+ Streams.asString(stream) + " detected.");
} else {
System.out.println("File field " + name + " with file name "
+ item.getName() + " detected.");
// Process the input stream
}
String mdrEntry = handleInput(name, stream);
mdrEntries.add(mdrEntry);
}
commitContent(mdrEntries);
}
示例6: doPost
import org.apache.commons.fileupload.FileItemStream; //导入方法依赖的package包/类
protected void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
long gameId = 0l;
String auth = null;
try {
ServletFileUpload upload = new ServletFileUpload();
FileItemIterator iter = upload.getItemIterator(req);
String json = "";
while (iter.hasNext()) {
FileItemStream item = iter.next();
String name = item.getFieldName();
InputStream stream = item.openStream();
if (item.isFormField()) {
String value = Streams.asString(stream);
if ("gameId".equals(name)) gameId = Long.parseLong(value);
if ("auth".equals(name)) auth = value;
} else {
json = Streams.asString(stream);
}
}
res.setContentType("text/plain");
JSONObject jObject = new JSONObject(json);
Object deserialized = JsonBeanDeserializer.deserialize(json);
if (deserialized instanceof GamePackage && ((GamePackage) deserialized).getGame() != null)
unpackGame((GamePackage) deserialized, req, auth);
if (deserialized instanceof RunPackage && ((RunPackage) deserialized ).getRun() != null)
unpackRun((RunPackage) deserialized, req, gameId, auth);
} catch (Exception ex) {
throw new ServletException(ex);
}
}
示例7: uploadMultipart
import org.apache.commons.fileupload.FileItemStream; //导入方法依赖的package包/类
private void uploadMultipart(HttpServletRequest req, HttpServletResponse resp,
OutputStream repoItemOutputStrem) throws IOException {
log.debug("Multipart detected");
ServletFileUpload upload = new ServletFileUpload();
try {
// Parse the request
FileItemIterator iter = upload.getItemIterator(req);
while (iter.hasNext()) {
FileItemStream item = iter.next();
String name = item.getFieldName();
try (InputStream stream = item.openStream()) {
if (item.isFormField()) {
// TODO What to do with this?
log.debug("Form field {} with value {} detected.", name, Streams.asString(stream));
} else {
// TODO Must we support multiple files uploading?
log.debug("File field {} with file name detected.", name, item.getName());
log.debug("Start to receive bytes (estimated bytes)",
Integer.toString(req.getContentLength()));
int bytes = IOUtils.copy(stream, repoItemOutputStrem);
resp.setStatus(SC_OK);
log.debug("Bytes received: {}", Integer.toString(bytes));
}
}
}
} catch (FileUploadException e) {
throw new IOException(e);
}
}
示例8: asMultipartRequest
import org.apache.commons.fileupload.FileItemStream; //导入方法依赖的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;
}
示例9: doPost
import org.apache.commons.fileupload.FileItemStream; //导入方法依赖的package包/类
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
ServletFileUpload upload = new ServletFileUpload();
try{
FileItemIterator iterator = upload.getItemIterator(request);
if (iterator.hasNext()) {
FileItemStream item = iterator.next();
String name = item.getFieldName();
logger.debug("Uploading file '{}' with item name '{}'", item.getName(), name);
InputStream stream = item.openStream();
ByteArrayOutputStream out = new ByteArrayOutputStream();
Streams.copy(stream, out, true);
byte[] data = out.toByteArray();
response.setStatus(HttpServletResponse.SC_OK);
response.setContentType("text/html");
response.setCharacterEncoding("utf-8");
response.getWriter().print(new String(data));
response.flushBuffer();
}
else {
logger.error("No file found in post request!");
throw new RuntimeException("No file found in post request!");
}
}
catch(Exception e){
logger.error("Unexpected error in FileUploadServlet.doPost: ", e);
throw new RuntimeException(e);
}
}
示例10: doPost
import org.apache.commons.fileupload.FileItemStream; //导入方法依赖的package包/类
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//CHECKSTYLE:ON
ServletFileUpload upload = new ServletFileUpload();
try {
FileItemIterator iter = upload.getItemIterator(request);
if (iter.hasNext()) {
FileItemStream item = iter.next();
String name = item.getFieldName();
LOG.debug("Uploading file '{}' with item name '{}'", item.getName(), name);
InputStream stream = item.openStream();
// Process the input stream
ByteArrayOutputStream out = new ByteArrayOutputStream();
Streams.copy(stream, out, true);
byte[] data = out.toByteArray();
cacheService.uploadedFile(name, data);
} else {
LOG.error("No file found in post request!");
throw new RuntimeException("No file found in post request!");
}
} catch (Exception ex) {
LOG.error("Unexpected error in FileUpload.doPost: ", ex);
throw new RuntimeException(ex);
}
}
示例11: FormPart
import org.apache.commons.fileupload.FileItemStream; //导入方法依赖的package包/类
public FormPart(FileItemStream stream) {
fieldName = stream.getFieldName();
contentType = stream.getContentType();
binaryContent = readBinaryContent(stream);
fileName = stream.getName();
if(contentType == null || contentType.contains(MediaType.TEXT_PLAIN)) {
textContent = new String(binaryContent);
}
}
示例12: doFilter
import org.apache.commons.fileupload.FileItemStream; //导入方法依赖的package包/类
@Override
public void doFilter(HttpExchange exchange, Chain chain) throws IOException
{
final Map<String, List<String>> params = parseGetParameters(exchange);
Map<String, Pair<String, File>> streams = null;
if( HttpExchangeUtils.isPost(exchange) )
{
if( HttpExchangeUtils.isMultipartContent(exchange) )
{
streams = new HashMap<String, Pair<String, File>>();
try
{
FileItemIterator ii = new FileUpload().getItemIterator(new ExchangeRequestContext(exchange));
while( ii.hasNext() )
{
final FileItemStream is = ii.next();
final String name = is.getFieldName();
try( InputStream stream = is.openStream() )
{
if( !is.isFormField() )
{
// IE passes through the full path of the file,
// where as Firefox only passes through the
// filename. We only need the filename, so
// ensure that we string off anything that looks
// like a path.
final String filename = STRIP_PATH_FROM_FILENAME.matcher(is.getName()).replaceFirst(
"$1");
final File tempfile = File.createTempFile("equella-manager-upload", "tmp");
tempfile.getParentFile().mkdirs();
streams.put(name, new Pair<String, File>(filename, tempfile));
try( OutputStream out = new BufferedOutputStream(new FileOutputStream(tempfile)) )
{
ByteStreams.copy(stream, out);
}
}
else
{
addParam(params, name, Streams.asString(stream));
}
}
}
}
catch( Exception t )
{
throw new RuntimeException(t);
}
}
else
{
try( InputStreamReader isr = new InputStreamReader(exchange.getRequestBody(), "UTF-8") )
{
BufferedReader br = new BufferedReader(isr);
String query = br.readLine();
parseQuery(query, params);
}
}
}
exchange.setAttribute(PARAMS_KEY, params);
exchange.setAttribute(MULTIPART_STREAMS_KEY, streams);
// attributes seem to last the life of a session... I don't know why...
exchange.setAttribute("error", null);
chain.doFilter(exchange);
}
示例13: getStreams
import org.apache.commons.fileupload.FileItemStream; //导入方法依赖的package包/类
/**
*
* @param req
* @param rpcRequest
* @param service
* @return
* @throws Exception
*/
private Map<String, InputStream> getStreams(HttpServletRequest req, RpcRequest rpcRequest, HttpAction service) throws Exception {
if (!FileUploadBase.isMultipartContent(new ServletRequestContext(req))) {
return null;
}
int streamsNumber = getInputStreamsNumber(rpcRequest, service);
boolean isResponseStreamed = service.isBinaryResponse();
FileItemIterator iter = (FileItemIterator) req.getAttribute(REQ_ATT_MULTIPART_ITERATOR);
int count = 0;
final Map<String, InputStream> map = new HashMap();
final File tempDirectory;
if (streamsNumber > 1 || streamsNumber == 1 && isResponseStreamed) {
tempDirectory = createTempUploadDirectory();
req.setAttribute(REQ_ATT_TEMPORARY_FOLDER, tempDirectory);
} else {
tempDirectory = null;
}
FileItemStream item = (FileItemStream) req.getAttribute(REQ_ATT_MULTIPART_CURRENT_ITEM);
long availableLength = RpcConfig.getInstance().getMaxRequestSize();
while (item != null) {
count++;
long maxLength = Math.min(availableLength, RpcConfig.getInstance().getMaxFileSize());
if (count < streamsNumber || isResponseStreamed) { // if response is streamed all inputstreams have to be readed first
File file = new File(tempDirectory, item.getFieldName());
FileOutputStream fos = new FileOutputStream(file);
try {
Miscellaneous.pipeSynchronously(new LimitedLengthInputStream(item.openStream(), maxLength), fos);
} catch (MaxLengthExceededException ex) {
if (maxLength == RpcConfig.getInstance().getMaxFileSize()) {
throw new MaxLengthExceededException("Upload part '" + item.getFieldName() + "' exceeds maximum length (" + RpcConfig.getInstance().getMaxFileSize() + " bytes)", RpcConfig.getInstance().getMaxFileSize());
} else {
throw new MaxLengthExceededException("Request exceeds maximum length (" + RpcConfig.getInstance().getMaxRequestSize() + " bytes)", RpcConfig.getInstance().getMaxRequestSize());
}
}
map.put(item.getFieldName(), new MetaDataInputStream(new FileInputStream(file), item.getName(), item.getContentType(), file.length(), null));
availableLength -= file.length();
} else if (count == streamsNumber) {
map.put(item.getFieldName(), new MetaDataInputStream(new LimitedLengthInputStream(item.openStream(), maxLength), item.getName(), item.getContentType(), null, null));
break;
}
req.setAttribute(REQ_ATT_MULTIPART_CURRENT_ITEM, item);
if (iter.hasNext()) {
item = iter.next();
} else {
item = null;
}
}
if (count != streamsNumber) {
throw new IllegalArgumentException("Invalid multipart request received. Number of uploaded files (" + count + ") does not match expected (" + streamsNumber + ")");
}
return map;
}
示例14: service
import org.apache.commons.fileupload.FileItemStream; //导入方法依赖的package包/类
@Override
public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// Check that we have a file upload request
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if (isMultipart) {
List<String> files = new ArrayList<>();
ServletFileUpload upload = new ServletFileUpload();
// Parse the request
FileItemIterator iter = null;
try {
iter = upload.getItemIterator(request);
while (iter.hasNext()) {
FileItemStream item = iter.next();
String name = item.getFieldName();
try (InputStream stream = item.openStream()) {
if (item.isFormField()) {
LOGGER.debug("Form field " + name + " with value " + Streams.asString(stream) + " detected.");
incrementStringsProcessed();
} else {
LOGGER.debug("File field " + name + " with file name " + item.getName() + " detected.");
// Process the input stream
File tmpFile = File.createTempFile(UUID.randomUUID().toString() + "_MockUploadServlet", ".tmp");
tmpFile.deleteOnExit();
try (OutputStream os = new FileOutputStream(tmpFile)) {
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = stream.read(buffer)) != -1) {
os.write(buffer, 0, bytesRead);
}
incrementFilesProcessed();
files.add(tmpFile.getAbsolutePath());
}
}
}
}
} catch (FileUploadException e) {
}
try (Writer w = response.getWriter()) {
w.write(Integer.toString(getFilesProcessed()));
resetFilesProcessed();
resetStringsProcessed();
w.write("||");
w.write(files.toString());
}
} else {
try (Writer w = response.getWriter()) {
w.write(Integer.toString(getFilesProcessed()));
resetFilesProcessed();
resetStringsProcessed();
w.write("||");
}
}
}
示例15: uploadFiles
import org.apache.commons.fileupload.FileItemStream; //导入方法依赖的package包/类
/**
* 파일을 Upload 처리한다.
*
* @param request
* @param where
* @param maxFileSize
* @return
* @throws Exception
*/
public static List<FormBasedFileVo> uploadFiles(
HttpServletRequest request,
String where,
long maxFileSize) throws Exception {
List<FormBasedFileVo> list = new ArrayList<FormBasedFileVo>();
// Check that we have a file upload request
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if (isMultipart) {
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload();
upload.setFileSizeMax(maxFileSize); // SizeLimitExceededException
// Parse the request
FileItemIterator iter = upload.getItemIterator(request);
while (iter.hasNext()) {
FileItemStream item = iter.next();
String name = item.getFieldName();
InputStream stream = item.openStream();
if (item.isFormField()) {
// System.out.println("Form field '" + name + "' with value '" + Streams.asString(stream) +
// "' detected.");
LOG.info("Form field '" + name + "' with value '" + Streams.asString(stream) + "' detected.");
} else {
// System.out.println("File field '" + name + "' with file name '" + item.getName() + "' detected.");
LOG.info("File field '" + name + "' with file name '" + item.getName() + "' detected.");
if ("".equals(item.getName())) {
continue;
}
// Process the input stream
FormBasedFileVo vo = new FormBasedFileVo();
String tmp = item.getName();
if (tmp.lastIndexOf("\\") >= 0) {
tmp = tmp.substring(tmp.lastIndexOf("\\") + 1);
}
vo.setFileName(tmp);
vo.setContentType(item.getContentType());
vo.setServerSubPath(getTodayString());
vo.setPhysicalName(getPhysicalFileName());
if (tmp.lastIndexOf(".") >= 0) {
vo.setPhysicalName(vo.getPhysicalName() + tmp.substring(tmp.lastIndexOf(".")));
}
long size = saveFile(stream,
new File(WebUtil.filePathBlackList(where) + SEPERATOR + vo.getServerSubPath() + SEPERATOR + vo.getPhysicalName()));
vo.setSize(size);
list.add(vo);
}
}
} else {
throw new IOException("form's 'enctype' attribute have to be 'multipart/form-data'");
}
return list;
}