I have jsp oage which upload form data and file upload also same time. But i got java.io.FileNotFoundException: when there isn't file upload - forms

boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if (isMultipart) {
System.out.println("multipart2");
// Create a factory for disk-based file items
FileItemFactory factory = new DiskFileItemFactory();
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
try {
// Parse the request
List /* FileItem */ items = upload.parseRequest(request);
Iterator iterator = items.iterator();
while (iterator.hasNext()) {
FileItem item = (FileItem) iterator.next();
if (item.isFormField()) //your code for getting form fields
{
if (item.getFieldName().equals("btn")) {
if (item.getString().equals("Submit")) {
String name = item.getFieldName();
String value = item.getString();
System.out.println("test2" + name + value);
}
if (item.getString().equals("Save as Draft")) {
System.out.println("hii hii2");
String name = item.getFieldName();
String value = item.getString();
}
}
} if (!item.isFormField()) {
String fileName = item.getName();
System.out.println("File Upload Named : " + fileName);
String root = getServletContext().getRealPath("/");
File path = new File(root + "/uploads");
if (!path.exists()) {
boolean status = path.mkdirs();
}
File uploadedFile = new File(path + "/" + fileName);
// System.out.println(uploadedFile.getAbsolutePath());
item.write(uploadedFile);
}
}
} catch (FileUploadException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
response.sendRedirect("/EventCalendar-war/pages/user_pages/user_create_event.jsp");
}
This is my code.When there is no file to upload I got java.io.FileNotFoundException .If file is upload with form data it's work fine.What is wrong with my code?

Related

Downloading images and save to device

I having some issues here with UnityWebRequest.
I tried to download and save the jpeg, but it seem that the download is a success but it does not save it, and does not show me Log from "saveToFile" function.
Did I did something wrong?
Here are my code.
public string folderPath;
void Start()
{
folderPath = Application.persistentDataPath + "/" + FileFolderName;
}
IEnumerator DownloadingImage(Uri url2)
{
Debug.Log("Start Downloading Images");
using (UnityWebRequest uwr = UnityWebRequestTexture.GetTexture(url2))
{
// uwr2.downloadHandler = new DownloadHandlerBuffer();
yield return uwr.SendWebRequest();
if (uwr.isNetworkError || uwr.isHttpError)
{
Debug.Log(uwr.error);
}
else
{
Debug.Log("Success");
Texture myTexture = DownloadHandlerTexture.GetContent(uwr);
byte[] results = uwr.downloadHandler.data;
saveImage(folderPath, results);
}
}
}
void saveImage(string path, byte[] imageBytes)
{
//Create Directory if it does not exist
if (!Directory.Exists(Path.GetDirectoryName(path)))
{
Directory.CreateDirectory(Path.GetDirectoryName(path));
Debug.Log("Creating now");
}
else
{
Debug.Log(path + " does exist");
}
try
{
File.WriteAllBytes(path, imageBytes);
Debug.Log("Saved Data to: " + path.Replace("/", "\\"));
}
catch (Exception e)
{
Debug.LogWarning("Failed To Save Data to: " + path.Replace("/", "\\"));
Debug.LogWarning("Error: " + e.Message);
}
}
You have wrong file name so give filename with extension,
If you don't give extension, 'Directory.Exists' doesn't know whether file or directory.
or you could separate parameters such as rootDirPath and filename.
IEnumerator DownloadingImage(Uri url2)
{
Debug.Log("Start Downloading Images");
using (UnityWebRequest uwr = UnityWebRequestTexture.GetTexture(url2))
{
// uwr2.downloadHandler = new DownloadHandlerBuffer();
yield return uwr.SendWebRequest();
if (uwr.isNetworkError || uwr.isHttpError)
{
Debug.Log(uwr.error);
}
else
{
Debug.Log("Success");
Texture myTexture = DownloadHandlerTexture.GetContent(uwr);
byte[] results = uwr.downloadHandler.data;
string filename = gameObject.name+".dat";
// saveImage(folderPath, results); // Not a folder path
saveImage(folderPath+"/"+filename, results); // give filename
}
}
}

“An error occured while executing doInBackground()”

i'm using the below code to get the file length and using which i display progress bar till i download the total file but i get an error from firebase crash report like below
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:304)
#Override
protected String doInBackground(String...Url) {
try {
URL url = new URL(Url[0]);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("HEAD");
connection.connect();
// Detect the file lenghth
fileLength = connection.getContentLength();
} else {
URLConnection connection = url.openConnection();
connection.connect();
// Detect the file lenghth
fileLength = connection.getContentLength();
}
/*
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("HEAD");
connection.connect();
int fileLength = connection.getContentLength();*/
// Locate storage location
// String filepath = Environment.getExternalStorageDirectory().getPath();
String filepath = getFilesDirectory(getApplicationContext()).getPath();
// File fo = getFilesDirectory(getApplicationContext());
// Download the file
InputStream input = new BufferedInputStream(url.openStream());
// Save the downloaded file
if (lang_slector == 0) {
// input stream to read file - with 8k buffer
File folder = new File(filepath, "/offlinedata/");
folder.mkdir();
File pdfFile = new File(folder, englishpdffilename);
try {
pdfFile.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
OutputStream output = new FileOutputStream(filepath + "/offlinedata/" +
pdffilename);
byte data[] = new byte[1024];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
total += count;
// Publish the progress
publishProgress((int)(total * 100 / fileLength));
output.write(data, 0, count);
}
// Close connection
output.flush();
output.close();
input.close();
} else if (lang_slector == 1) {
// input stream to read file - with 8k buffer
File folder = new File(filepath, "/offlinedata/");
folder.mkdir();
File pdfFile = new File(folder, englishpdffilename);
try {
pdfFile.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
OutputStream output = new FileOutputStream(filepath + "/offlinedata/" +
englishpdffilename);
byte data[] = new byte[1024];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
total += count;
// Publish the progress
publishProgress((int)(total * 100 / fileLength));
output.write(data, 0, count);
}
// Close connection
output.flush();
output.close();
input.close();
}
} catch (Exception e) {
// Error Log
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}

How do i return a powerpoint (.pptx) file from REST response in springMVC

I am generating a powerpoint file(.pptx) and i would like to return back this file when a REST call happens. But now am able to get only .File type extension.
#RequestMapping(value = "/ImageManagerPpt/{accessionId}", method = RequestMethod.GET, produces = "application/ppt")
public ResponseEntity<InputStreamResource> createPptforAccessionId(#PathVariable("accessionId") String accessionId,HttpServletResponse response) throws IOException** {
System.out.println("Creating PPT for Patient Details with id " + accessionId);
File pptFile = imageManagerService.getPptForAccessionId(accessionId);
if (pptFile == null) {
System.out.println("Patient Id with id " + accessionId + " not found");
return new ResponseEntity<InputStreamResource>(HttpStatus.NOT_FOUND);
}
InputStream stream = null;
try {
stream = new FileInputStream(pptFile);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ClassPathResource classpathfile = new ClassPathResource("Titlelayout3.pptx");
InputStreamResource inputStreamResource = new InputStreamResource(stream);
return ResponseEntity.ok().contentLength(classpathfile.contentLength())
.contentType(MediaType.parseMediaType("application/octet-stream"))
.body(new InputStreamResource(classpathfile.getInputStream()));
}
-Bharat
Have you tried, this?
InputStream stream = new InputStream(pptFile);
org.apache.commons.io.IOUtils.copy(is, response.getOutputStream());
response.flushBuffer();
You will get file as you put into the InputStream.

Uploading file whose name is in unicode

I have some JavaScript code that upload file to server using ajax and form data and server side java code that accept it. I can upload English file name. But when I uploaded other Unicode file name, the file name I got in server side is unreadable. The following is code snippet.
JavaScript
var f = new FormData();
f.append("file", file);
xhr.send(f);
Java
public void upload(MultipartFormDataInput input) {
Map<String, List<InputPart>> uploadForm = input.getFormDataMap();
List<InputPart> inputParts = uploadForm.get("user_file[]");
IFileInfo file = null;
for (InputPart inputPart : inputParts) {
try {
MultivaluedMap<String, String> header = inputPart.getHeaders();
fileName = getFileName(header);
System.out.println("File name is " + fileName);
} catch (IOException e) {
e.printStackTrace();
}
}
}
private String getFileName(MultivaluedMap<String, String> header) {
System.out.println("Headers is " + header.getFirst("Content-Disposition"));
String[] contentDisposition = header.getFirst("Content-Disposition")
.split(";");
for (String filename : contentDisposition) {
if ((filename.trim().startsWith("filename"))) {
String[] name = filename.split("=");
String finalFileName = name[1].trim().replaceAll("\"", "");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return finalFileName;
}
}
return "unknown";
}
When I upload "大家好.jpg" , I got server side log showing the following.
Headers is form-data; name="user_file[]"; filename="���������.jpg"
File name is ���������.jpg
I think browser encode file name before uploading it.But I don't know which encoding did it used or how to decode it back. Any help is much appreciated.

Send a file from server to client in GWT

I am using GWT.
I have to download a file file from server to client.
Document is in the external repository.
Client sends the id of the document through a Servlet.
On server side: Using this ID document is retrieved:
Document document = (Document)session.getObject(docId);
ContentStream contentStream = document.getContentStream();
ByteArrayInputStream inputStream = (ByteArrayInputStream) contentStream.getStream();
int c;
while ((c = inputStream.read()) != -1) {
System.out.print((char) c);
}
String mime = contentStream.getMimeType();
String name = contentStream.getFileName();
InputStream strm = contentStream.getStream();
Here I can read the document.
I want to send this to the client.
How do I make this a file and send it back to the client?
In Your Servlet:
Document document =(Document)session.getObject(docId);
ContentStream contentStream = document.getContentStream();
String name = contentStream.getFileName();
response.setHeader("Content-Type", "application/octet-stream;");
response.setHeader("Content-Disposition", "attachment;filename=\"" + name + "\"");
OutputStream os = response.getOutputStream();
InputStream is =
(ByteArrayInputStream) contentStream.getStream();
BufferedInputStream buf = new BufferedInputStream(is);
int readBytes=0;
while((readBytes=buf.read())!=-1) {
os.write(readBytes);
}
os.flush();
os.close();// *important*
return;
You can create a standard servlet (which extends HttpServlet and not RemoteServiceServlet) on server side and opportunity to submit the id as servlet parameter on client side.
Now you need after getting request create the excel file and send it to the client. Browser shows automatically popup with download dialog box.
But you should make sure that you set the right content-type response headers. This header will instruct the browser which type of file is it.
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String fileId = reguest.getParameter("fileId"); // value of file id from request
File file = CreatorExel.getFile(fileId); // your method to create file from helper class
// setting response headers
response.setHeader("Content-Type", getServletContext().getMimeType(file.getName()));
response.setHeader("Content-Length", file.length());
response.setHeader("Content-Disposition", "inline; filename=\"" + file.getName() + "\"");
BufferedInputStream input = null;
BufferedOutputStream output = null;
try {
InputStream inputStream = new FileInputStream(file);
ServletOutputStream outputStream = response.getOutputStream();
input = new BufferedInputStream(fileInput);
output = new BufferedOutputStream(outputStream);
int count;
byte[] buffer = new byte[8192]; // buffer size is 512*16
while ((count = input.read(buffer)) > 0) {
output.write(buffer, 0, count);
}
} finally {
if (output != null) {
try {
output.close();
} catch (IOException ex) {
}
}
if (input != null) {
try {
input.close();
} catch (IOException ex) {
}
}
}