Apache common file upload empty multipart item list - file

I have been trying to parse a multipart request by using apache commons file upload over JBOSS 5.1 .
The problem is when request is parsed, FileItem list is not being filled .(FileItem list is empty) Here is the code block that is working on windows but not on Unix :
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold(1024*1024*3);
factory.setRepository(new File("/root/loads/temp"));
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setFileSizeMax(100000);
upload.setSizeMax(100000);
boolean isMulti =upload.isMultipartContent(request);
// Parse the request
try {
List<FileItem> items = upload.parseRequest(request);
Note : I am reaching the HTTPServletRequest via HttpEvent.getHTTPServletRequest().Also request has not being handled before.java version = 1.6_021

I found the solution, jboss security and our project's platform rules does not allow to access any file which are not in the specified directory.
I used jboss temp directory and can access the items in the request.

Related

Trying to retrieve a file from another computer on same network

I am trying to copy an image file from a computer on the same network as mine, but running into an exception.
I am running as aspnet core app on a Raspberry Pi. The computer with the image is an android device on the same network.
The address of the image to be copied is: ftp://172.18.10.190:8010/records/2019-07-26/157395.jpg
I can put that link into a browser and retrieve the image, but I would like to save it to the Pi.
I have tried using File.Copy:
System.IO.File.Copy("ftp://172.18.10.190:8010/records/2019-07-26/157395.jpg", directory + "/" + "157395.jpg");
I am getting a directory not found error:
NotFoundException: Could not find a part of the path 'home/pi/pcmonitor/ftp:/172.18.10.190:8010/records/2019-07-26/157395.jpg'
It looks like the 'home/pi/pcmonitor/'is being pre-pended along with one of the forward slashes after ftp being deleted.
You could not copy or download ftp file through File.Copy.
You need to send request and save the response like
// Get the object used to communicate with the server.
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftpPath);
request.Method = WebRequestMethods.Ftp.DownloadFile;
// This example assumes the FTP site uses anonymous logon.
request.Credentials = new NetworkCredential("xx", "xx");
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
Stream responseStream = response.GetResponseStream();
using (var fileStream = File.Create(localPath))
{
responseStream.CopyTo(fileStream);
}
Console.WriteLine($"Download Complete, status {response.StatusDescription}");
response.Close();

Browser data storage location for "Choose File" button

For web browsers (such as Chrome, IE, or Firefox), when you select a file using a "Choose File" button, where does the file's data get stored?
The file name shows in the browser, but does the data of the file get stored anywhere or is just a link to the file put somewhere, such as in the browser or a temporary file?
To clarify: I want to know where the file's data get's stored BEFORE submitting. JUST after the file is selected from the client's PC an not anything else is done.
After you select a file. I believe the client (browser) just stores a reference to the file location on the user's computer. It takes a combination of js and html to post the file to the server. Via a Multi/form-data Post.
In this case, on the server, you may have to store the file to a temp location of your choosing, until you're able to process it (i.e. transform and/or store to a Datastore).
In newer browsers you can use the FormData object and xhr to post to the server which is a lot cleaner.
This FormData object is used to construct the key/value pairs which form the data payload for the xhr request.
// Create a new FormData object.
var formData = new FormData();
In this case, once the file bytes are posted to the server, you can do whatever you want with that data. Typically I'll store it as a blob in the DB.
This approach will allow you to keep it all in memory. People make the mistake of trying to store on the server file system. In some multipart form post, you might have to do it this way, however.
Here's some of my web api upload code when using XHR.
I've also called this API route using an iframe (ugh!) in order to support IE8 and older. POS browsers!
/// <summary>
/// Upload the facility logo.
/// </summary>
/// <returns></returns>
[HttpPost]
[Route("logo")]
public HttpResponseMessage Logo()
{
int newImageId = -1;
var uploadedFiles = HttpContext.Current.Request.Files;
if (uploadedFiles.Count > 0)
{
var file = uploadedFiles[0];
if (!file.IsImage())
{
// "The uploaded file must be a .jpg, .jpeg, or .png"
return
Request.CreateResponse(HttpStatusCode.UnsupportedMediaType,
"unsupported");
}
var facilityRepository = new FacilityRepository();
var logoBytes =
StreamCopier.StreamToByteArray(file.InputStream, file.ContentLength);
newImageId = facilityRepository.InsertLogoImage(logoBytes);
}
return Request.CreateResponse(HttpStatusCode.OK,
newImageId);
}

Swagger UI how to display upload of multiple files

I've a Spring MVC application that is wrapped with Swagger annotations.
<spring.version>4.1.8.RELEASE</spring.version>
<java-version>1.7</java-version>
<springfox-version>2.1.2</springfox-version>
I've a controller with two resource endpoints to allow file upload - one endpoint for a single file upload and other with multiple file upload.
Single file upload -->
public #ResponseBody UploadAPIResponse postInboundFile(
#ApiParam(value = "file to upload") #RequestParam("file") MultipartFile file,
#ApiParam(value = "Inbound trigger flag ") #RequestParam("triggerInbound") Boolean triggerInbound)
throws SQLException, Exception {
Multi file upload -->
public #ResponseBody BulkUploadAPIResponse postInboundFilesAsync(
#ApiParam(value = "files to upload") #RequestParam("files") MultipartFile[] files,
#ApiParam(value = "Inbound trigger flag ") #RequestParam("triggerInbound") Boolean triggerInbound,
HttpServletRequest request) throws SQLException, Exception {
On viewing the Swagger UI for the api documentation,
I see that for single file upload API, against the "file" parameter, I get a file upload button.
However for the multi file upload API, I get the "files" parameter as a text box.
Can someone pls help me how can I get a file upload button against the "files" parameter of multi-files upload API and I'm able to upload multiple files as part of single request ?
I've gone through various other posts on this context but not able to find a concrete approach to address this issue.
PS : I've the understanding that naming the parameter as "file" provides the file upload button automatically through Swagger-UI. I tried to use the parameter name as "file" instead of "files" for the multi-file upload API but that didn't help; i still end up getting a text box (probably reason being that argument is an array of MultipartFile).
Thanks in advance for any pointers/suggestions.

CXF wsdl2java, GZip compression, and stub reutilization

I´m using CXF to consume a WebService and, as the responses are quite large, I´m requesting with a gzip "Accept-Encoding" and using GZIPInInterceptor to handle the gziped response. Also my WSDL is very large (360kb) and it takes a long time(+10 seconds) to create the stub, because it has to read and parse the WSDL, so I´m creating the stub once and reusing it.
The problem is, whenever I try to use two different methods the second request gives me an error saying it is expecting the previous request.
To illustrate my problem I created a simple example with this public WebService:
http://www.webservicex.net/BibleWebservice.asmx?WSDL
Without the GZip compression it works fine:
BibleWebserviceSoap bibleService = new BibleWebservice().getBibleWebserviceSoap();
String title = bibleService.getBookTitles();
response.getWriter().write(title);
String johnResponse = bibleService.getBibleWordsbyKeyWord("John");
response.getWriter().write(johnResponse);
I´m able to receive both responses.
Enabling Gzip compression:
BibleWebserviceSoap bibleService = new BibleWebservice().getBibleWebserviceSoap();
//GZIP compression on bibleService
Client client = ClientProxy.getClient(bibleService);
client.getInInterceptors().add(new GZIPInInterceptor());
client.getInFaultInterceptors().add(new GZIPInInterceptor());
// Creating HTTP headers
Map<String, List<String>> headers = new HashMap<String, List<String>>();
headers.put("Accept-Encoding", Arrays.asList("gzip"));
// Add HTTP headers to the web service request
client.getRequestContext().put(Message.PROTOCOL_HEADERS, headers);
String title = bibleService.getBookTitles();
response.getWriter().write(title);
String johnResponse = bibleService.getBibleWordsbyKeyWord("John");
response.getWriter().write(johnResponse);
When I try to receive the second response I´m getting this exception:
org.apache.cxf.interceptor.Fault: Unexpected wrapper element {http://www.webserviceX.NET}GetBookTitlesResponse found. Expected {http://www.webserviceX.NET}GetBibleWordsbyKeyWordResponse.
On my real application I´m getting an exception with the request:
org.apache.cxf.binding.soap.SoapFault: OperationFormatter encountered an invalid Message body. Expected to find node type 'Element' with name 'GetAvailabilityRequest' and namespace 'http://schemas.navitaire.com/WebServices/ServiceContracts/BookingService'. Found node type 'Element' with name 'ns4:PriceItineraryRequest' and namespace 'http://schemas.navitaire.com/WebServices/ServiceContracts/BookingService'
My sample project can be downloaded here:
http://www.sendspace.com/file/plt0m4
Thank you
Instead of setting the protocol headers directly like that, use CXF's GZIPOutInterceptor to handle that.
Either that or reset the PROTOCOL headers for each request. When set like that, the headers map gets updated as the request goes through the chain. In this case, the soapaction gets set. This then gets resent on the second request.

How can I upload a file to a Sharepoint Document Library using Silverlight and client web-services?

Most of the solutions I've come across for Sharepoint doc library uploads use the HTTP "PUT" method, but I'm having trouble finding a way to do this in Silverlight because it has restrictions on the HTTP Methods. I visited this http://msdn.microsoft.com/en-us/library/dd920295(VS.95).aspx to see how to allow PUT in my code, but I can't find how that helps you use an HTTP "PUT".
I am using client web-services, so that limits some of the Sharepoint functions available.
That leaves me with these questions:
Can I do an http PUT in Silverlight?
If I can't or there is another better way to upload a file, what is it?
Thanks
Figured it out!! works like a charm
public void UploadFile(String fileName, byte[] file)
{
// format the destination URL
string[] destinationUrls = {"http://qa.sp.dca/sites/silverlight/Answers/"+fileName};
// fill out the metadata
// remark: don't set the Name field, because this is the name of the document
SharepointCopy.FieldInformation titleInformation = new SharepointCopy.FieldInformation
{DisplayName =fileName,
InternalName =fileName,
Type = SharepointCopy.FieldType.Text,
Value =fileName};
// to specify the content type
SharepointCopy.FieldInformation ctInformation = new SharepointCopy.FieldInformation
{DisplayName ="XML Answer Doc",
InternalName ="ContentType",
Type = SharepointCopy.
FieldType.Text,
Value ="xml"};
SharepointCopy.FieldInformation[] metadata = { titleInformation };
// initialize the web service
SharepointCopy.CopySoapClient copyws = new SharepointCopy.CopySoapClient();
// execute the CopyIntoItems method
copyws.CopyIntoItemsCompleted += copyws_CopyIntoItemsCompleted;
copyws.CopyIntoItemsAsync("http://null", destinationUrls, metadata, file);
}
Many Thanks to Karine Bosch for the solution here: http://social.msdn.microsoft.com/Forums/en/sharepointdevelopment/thread/f135aaa2-3345-483f-ade4-e4fd597d50d4
What type of SharePoint deployment and what version of silverlight? If say it is an intranet deployment you could use UNC paths to access your document library in sharepoint and the savefiledialog/openfiledialog available in Silverlight 3.
http://progproblems.blogspot.com/2009/11/saveread-file-from-silverlight-30-in.html
or
http://www.kirupa.com/blend_silverlight/saving_file_locally_pg1.htm
Silverlight has restrictions on what it can do with local files, though I've read that silverlight 4 has some changes.
http://www.wintellect.com/CS/blogs/jprosise/archive/2009/12/16/silverlight-4-s-new-local-file-system-support.aspx

Resources