I am trying to create a upload servlet that handles enctype="multipart/form-data" from a form. The file I am trying to upload is a zip. However, I can upload and read the file on localhost, but when I upload to the server, I get a "File not found" error when I want to upload a file. Is this due to the Struts framework that I am using? Thanks for your help. Here is part of my code, I am using FileUpload from http://commons.apache.org/fileupload/using.html
I have changed to using ZipInputStream, however, how to I reference to the ZipFile zip without using a local disk address (ie: C://zipfile.zip). zip is null because its not instantiated. I will need to unzip and read the zipentry in memory, without writing to the server.
For the upload servlet:
>
private ZipFile zip;
private CSVReader reader;
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if(isMultipart){
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
List <FileItem> items = upload.parseRequest(request);
Iterator iter = items.iterator();
while (iter.hasNext()) {
//Iterating through the uploaded zip file and reading the content
FileItem item = (FileItem) iter.next();
ZipInputStream input = new ZipInputStream(item.getInputStream());
ZipEntry entry = null;
while (( entry= input.getNextEntry()) != null) {
ZipEntry entry = (ZipEntry) e.nextElement();
if(entry.getName().toString().equals("file.csv")){
//unzip(entry)
}
}
}
public static void unzip(ZipEntry entry){
try{
InputStream inputStream = **zip**.getInputStream(entry);
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
reader = new CSVReader(inputStreamReader);
}
catch(Exception e){
e.printStackTrace();
}
}
<
Here,
zip = new ZipFile(new File(fileName));
You're assuming that the local disk file system at the server machine already contains the file with exactly the same name as it is at the client side. This is a wrong assumption. That it worked at localhost is obviously because both the webbrowser and webserver "by coincidence" runs at physically the same machine with the same disk file system.
Also, you seem to be using Internet Explorer as browser which incorrectly includes the full path in the filename like C:/full/path/to/file.ext. You shouldn't be relying on this browser specific bug. Other browsers like Firefox correctly sends only the file name like file.ext, which in turn would have caused a failure with new File(fileName) (which should have helped you to spot your mistake much sooner).
To fix this "problem", you need to obtain the file contents as InputStream by item.getInputStream():
ZipInputStream input = new ZipInputStream(item.getInputStream());
// ...
Or to write it to disk by item.write(file) and reference it in ZipFile:
File file = File.createTempFile("temp", ".zip");
item.write(file);
ZipFile zipFile = new ZipFile(file);
// ...
Note: don't forget to check the file extension beforehand, else this may choke.
Related
I'm trying to download a file using HTTP, and here is the code.
With this, I have a directory made with a correct name, and a file within the directory made with a correct name, but there is NOTHING WRITTEN in the file.
PostMethod post = new PostMethod(serverUrl);
post.setRequestEntity(entity);
httpclient.executeMethod(post);
File contentDirectory = new File(fileFullPath);
if(contentDirectory.exists() == false){
contentDirectory.mkdir();
}
File localFile = new File(fileFullPath + File.separator + filename);
int readBuf = 0;
byte[] buf = new byte[Utils.getBufferSize()]; (BufferSize Checked)
InputStream is = null;
is = post.getResponseBodyAsStream();
FileOutputStream fos = new FileOutputStream(localFile);
while((readBuf = is.read(buf))!= -1){
fos.write(buf, 0, readBuf);
logger.info("readBuf : "+readBuf);
}
is.close();
fos.close();enter code here
if(localFile.exists()) Transfer_Success = true;
Being a noob I am, turns out all this time I was sending post method to a wrong servlet. A mistake only novices make.
So I have the bytes transferred correctly, but this time the image files can't be open due to wrong encoding type or something. I'm on to resolving this.
I wrote a program that each user has an account, and they can change their head portrait. When they sign in, the directory "src/username/password" will be created, and the image "src/username/password/headPortrait.jpg" will also be created. Then the default headPortrait is expected to show on a label, but the problem occurs: an image is added to the "src/username/password" directory, but the src folder in eclipse is not refreshed, so the program can't find the added image and throws Exception. So, I must exit the program ,refresh the src folder and then run the program again. That's absolutely not what I expect. What should I do about that?
Here is the most important part of my code:
String username=name.getText(); //"name" is a TextField
String password=word.getText(); //"word" is a TextField
File namefile=new File("src/"+username);
File passwordfile=new File("src/"+username+"/"+password);
if(namefile.mkdirs()){
if(passwordfile.mkdirs()){
File default=new File("src/images/headPortrait.jpg");//the default fead portrait is previously put under this directory.
try{
FileInputStream in=new FileInputStream(default);
FileOutputStream out=new FileOutputStream("src/"+username+"/"+password+"/"+"headPortrait.jpg");
BufferedInputStream bufferedIn=new BufferedInputStream(in);
BufferedOutputStream bufferedOut=new BufferedOutputStream(out);
byte[] bytes=new byte[1];
while(bufferedIn.read(bytes)!=-1){
bufferedOut.write(bytes);
}
bufferedOut.flush();
bufferedIn.close();
bufferedOut.close();
}catch(IOException e){
e.printStackTrace();
}
//Here, the problem aready occurs! The folders and default
//portrait are successfully created but the src folder in eclipse
//is not refreshed, so the default portrait won't show up!
}else{
//show a failure message
}
}else{
//show a failure message
}
Label portrait=new Label();
ImageView userImage=new ImageView(new Image(this.getClass.getResouceAsStream("/"+username+"/"+password+"/"+headPortrait.jpg)));
portrait.setGraphic(userImage);
//And the userImage won't show up and throws Exception, because the src folder in eclipse is not refreshed!
This is not the approach you should use since it will would only work in the development environment. When you deploy your app the compiled code will most likely be contained in a .jar archive that the JVM accesses.
The way to go would be to store the data in a convenient place (server, user directory, ...) and load it from this source.
Example (user directory)
static Path appDirectory = new File(System.getProperty("user.home")).toPath().resolve("myapp");
static void copy(InputStream in, OutputStream out) throws IOException {
BufferedInputStream bufferedIn=new BufferedInputStream(in);
BufferedOutputStream bufferedOut=new BufferedOutputStream(out);
byte[] bytes = new byte[1024];
while(bufferedIn.read(bytes)!=-1){
bufferedOut.write(bytes);
}
}
String username=name.getText(); //"name" is a TextField
String password=word.getText(); //"word" is a TextField
Path passwordDirectory = appDirectory.resolve(Paths.get(username, password));
Path userImage = passwordDirectory.resolve("headPortrait.jpg");
Files.createDirectories(passwordDirectory);
try (InputStream in = getClass().getResourceAsStream("/images/headPortrait.jpg"); // make sure this image is included as resource
OutputStream out = Files.newOutputStream(userImage)) {
copy(in, out);
}
ImageView userImageView = new ImageView(new Image(userImage.toUri().toString()));
BTW: Creating a directory from user name and password seems to be a bad idea to me. The password may contain characters that must not be part of a file name after all... Also it would require you to move the files when the the password is changed... Not to mention the password is stored as plain text in a prominent place...
I am working on Xamarin.Forms-UWP.
I want to convert byte array stored in the database to pdf for Windows phone.
I know how to convert
var base64Binarystr = "ABCDS"
byte[] bytes = Convert.FromBase64String(base64Binarystr );
Can anyone help as how to display pdf? Just a pointer- I have multiple pdf files so I cannot add all the files to the application or store on the disk.
Appreciate for any pointers on this.
Thanks!
Every received file can be stored with the same name (I used "my.pdf") then there is no risk for too many files stored. If you need to cache files then you can give different names. The pdf viewer didn't want to show files from Local, Temp or Downloads folder for me though I tried ms-appdata, so I had to move the file from Local folder to Assets to display the way viewer "wants" it via ms-appx-web. Downloads folder also has a problem with CreationCollisionOption.ReplaceExisting, it says invalid parameter if file already exists instead of replacing it but Local and Temporary folder behave correctly.
/////////////// store pdf file from internet, move it to Assets folder and display ////////////////////
//bytes received from Internet. Simulated that by reading existing file from Assets folder
var pdfBytes = File.ReadAllBytes(#"Assets\Content\samplepdf.pdf");
try
{
StorageFolder storageFolder = ApplicationData.Current.LocalFolder; //or ApplicationData.Current.TemporaryFolder
StorageFile pdfFile = await storageFolder.CreateFileAsync("my.pdf", CreationCollisionOption.ReplaceExisting);
//write data to created file
await FileIO.WriteBytesAsync(pdfFile, pdfBytes);
//get asets folder
StorageFolder appInstalledFolder = Windows.ApplicationModel.Package.Current.InstalledLocation;
StorageFolder assetsFolder = await appInstalledFolder.GetFolderAsync("Assets");
//move file from local folder to assets
await pdfFile.MoveAsync(assetsFolder, "my.pdf", NameCollisionOption.ReplaceExisting);
}
catch (Exception ex)
{
}
Control.Source = new Uri(string.Format("ms-appx-web:///Assets/pdfjs/web/viewer.html?file={0}", "ms-appx-web:///Assets/my.pdf")); //local pdf
As the title suggests, WLP won't run the process- it won't return anything to the process input stream nor to error stream.
If anyone knows about a configuration that needs to take place I would love to know..
(note the process Can run by running the command manually - in addition, the whole thing runs smooth on tomcat8 so..)
EDIT 1:
The problem was not the command execution under WLP as you guys stated, so I accepted the answer.
The problem is different : I sent a media file to a multipart servlet and stored it in a file on disk using the following code:
InputStream is = request.getInputStream();
String currentTime = new Long(System.currentTimeMillis()).toString();
String fileName = PATH + currentTime + "." + fileType;
File file = new File(fileName);
// write the image to a temporary location
FileOutputStream os = new FileOutputStream(file);
byte[] buffer = new byte[BUFFER_SIZE];
while(true) {
int numRead = is.read(buffer);
if(numRead == -1) {
break;
}
os.write(buffer, 0, numRead);
os.flush();
}
is.close();
os.close();
and the file gets saved along with the following prefix:
While this does not happen on tomcat8 (using the same client)..
something is not trivial in the received input stream. (Note its a multipart servlet that set up via #MultipartConfig only)
Hope this post will help others..
guys,thanks for your help!
This will work in Liberty. I was able to test out the following code in a servlet and it printed the path of my current directory just fine:
String line;
Process p = Runtime.getRuntime().exec("cmd /c cd");
BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
while ((line = input.readLine()) != null) {
System.out.println(line);
}
input.close();
Start with a simple command like this, and when you move up to more complex commands or scripts, make sure you are not burying exceptions that may come back. Always at least print the stack trace!
I'm trying to upload a large file to a document library, but it fails after just a few seconds. The upload single document fails silently, upload multiple just shows a failed message. I've turned up the file size limit on the web application to 500MB, and the IIS request length to the same (from this blog), and increased the IIS timeout for good measure. Are there any other size caps that I've missed?
Update I've tried a few files of various sizes, anything 50MB or over fails, so I assume something somewhere is still set to the webapp default.
Update 2 Just tried uploading using the following powershell:
$web = Get-SPWeb http://{site address}
$folder = $web.GetFolder("Site Documents")
$file = Get-Item "C:\mydoc.txt" // ~ 150MB
$folder.Files.Add("SiteDocuments/mydoc.txt", $file.OpenRead(), $false)
and get this exception:
Exception calling "Add" with "3" argument(s): "<nativehr>0x80070003</nativehr><nativestack></nativestack>There is no file with URL 'http://{site address}/SiteDocuments/mydoc.txt' in this Web."
which strikes me as odd as of course the file wouldn't exist until it's been uploaded? N.B. while the document library has the name Site Documents, it has the URL SiteDocuments. Not sure why...
Are you sure you updated the right webapp? Is the filetype blocked by the server? Is there adequate space in your content database? I would check ULS logs after that and see if there is another error since it seems you hit the 3 spots you would need too update.
for uploading a large file, you can use the PUT method instead of using the other ways to upload a document.
by using a put method you will save the file into content database directly. see the example below
Note: the disadvantage of the code below is you cannot catch the object that is responsible for uploading directly, on other word, you cannot update the additional custom properties of the uploaded document directly.
public static bool UploadFileToDocumentLibrary(string sourceFilePath, string targetDocumentLibraryPath)
{
//Flag to indicate whether file was uploaded successfuly or not
bool isUploaded = true;
try
{
// Create a PUT Web request to upload the file.
WebRequest request = WebRequest.Create(targetDocumentLibraryPath);
//Set credentials of the current security context
request.Credentials = CredentialCache.DefaultCredentials;
request.Method = “PUT”;
// Create buffer to transfer file
byte[] fileBuffer = new byte[1024];
// Write the contents of the local file to the request stream.
using (Stream stream = request.GetRequestStream())
{
//Load the content from local file to stream
using (FileStream fsWorkbook = File.Open(sourceFilePath, FileMode.Open, FileAccess.Read))
{
//Get the start point
int startBuffer = fsWorkbook.Read(fileBuffer, 0, fileBuffer.Length);
for (int i = startBuffer; i > 0; i = fsWorkbook.Read(fileBuffer, 0, fileBuffer.Length))
{
stream.Write(fileBuffer, 0, i);
}
}
}
// Perform the PUT request
WebResponse response = request.GetResponse();
//Close response
response.Close();
}
catch (Exception ex)
{
//Set the flag to indiacte failure in uploading
isUploaded = false;
}
//Return the final upload status
return isUploaded;
}
and here are an example of calling this method
UploadFileToDocumentLibrary(#”C:\test.txt”, #”http://home-vs/Shared Documents/textfile.pdf”);