I've the following struts code. I'm trying to download a csv file but nothing happens when I click download. I don't get any errors and in javascript I get a successful response. Myy post function logs my csv content on browser console too. I can't see why the file download won't start downloading.
Here is my jsp:
<%# taglib prefix="s" uri="/struts-tags"%>
<div>
<div>
<h4>Information</h4>
<div class="tab-pane" id="login">
<div class="panel panel-default">
<form id = "info" class="form-horizontal">
<div >
<label>FName</label>
<span style="float:right"><s:property value="%{fName}"
</span>
</div>
<div>
<label>MName or Initial</label>
<span style="float:right"><s:property value="%{mName}"/></span>
</div>
<div>
<label>LName</label>
<span style="float:right"><s:property value="%{lName}"/></span>
</div>
</form>
</div>
</div>
</div>
<div class="footer">
<button type="button" class="btn btn-primary" onClick="download();">Download</button>
</div>
</div>
<script>
function download(){
var action = 'download.action';
var meth = 'post';
var fields = jQuery("#info").children();
var params = [];
for(var i=0; i<fields.length;i++){
var field = fields[i];
var nodes = jQuery(field).children();
if(nodes.length == 2){
params.push(encodeURIComponent(nodes[0].innerText)
+"="+
encodeURIComponent(nodes[1].innerText));
}
}
var encr = btoa(params.join('&'));
jQuery.post(action,"data="+encr,function(data,status,xhr){
console.log(data);
console.log(status);
console.log(xhr);
});
}
</script>
Action class
public class Downloads extends CustomActionClass{
private static final long serialVersionUID = 1L;
private String data;
private InputStream fileStream;
private long contentLength;
public String execute() {
String decodeData = new
String(java.util.Base64.getDecoder().decode(data));
List<String> downloadData = new ArrayList<String>();
try {
String fileName = "info.csv";
String [] dataList = URLDecoder.decode(decodeData,"UTF-8").split("&");
String header ="";
String vals = "";
for(String dat: dataList) {
String[] tData = dat.split("=");
header += tData[0] + ",";
if(tData.length>1)
vals += tData[1]+",";
}
if(StringUtils.isNotBlank(header))
downloadData.add(header.substring(0,header.length()-1));
if(StringUtils.isNotBlank(vals))
downloadData.add(vals.substring(0,vals.length()-1));
File fil = new File(getServerTempFolder()+fileName);
fil.createNewFile();
contentLength = fil.length();
FileUtils.writeLines(fil, "UTF-8", downloadData);
fileStream = new FileInputStream(fil);
} catch (Exception e) {
log.info("Error: " + e.getMessage());
log.debug(e.fillInStackTrace());
}
return SUCCESS;
}
/**
* #return the data
*/
public String getData() {
return data;
}
/**
* #param data the data to set
*/
public void setData(String data) {
this.data = data;
}
/**
* #return the fileStream
*/
public InputStream getFileStream() {
return fileStream;
}
/**
* #param fileStream the fileStream to set
*/
public void setFileStream(InputStream fileStream) {
this.fileStream = fileStream;
}
/**
* #return the contentLength
*/
public long getContentLength() {
return contentLength;
}
/**
* #param contentLength the contentLength to set
*/
public void setContentLength(long contentLength) {
this.contentLength = contentLength;
}
}
Here is my Struts Mapping:
<action name="download" class="com.util.Downloads">
<result name="success" type="stream">
<param name="contentType">application/octet-stream</param>
<param name="contentLength">${contentLength}</param>
<param name="inputName">fileStream</param>
<param name="contentDisposition">attachment;filename="info.csv"</param>
<param name="bufferSize">1024</param>
I have solved this issue. So the solution to this is that ajax call won't trigger the download since it's a post request. I had to do window.href=action; this made the get call and hence the stream was returned from the action class.
I'm going to go one step further in case anyone has encoding issues. To encode properly for pdf write correct headers to specify UTF-8 encoding.. for csv write this to file byte[] enc = new byte[] { (byte)0xEF, (byte)0xBB, (byte)0xBF }; before you start write your data to file. And yes you can write this byte stream and then write String data to file.
Refer to this link for CSV http://smallbusiness.chron.com/utf8-encoding-excel-using-java-47939.html ...
Related
I am making a simple CRUD function for a bill management system. It uses Jquery AJAX JSON to communicate to the servlets.
The update and delete functions are activated by buttons in a dynamically generated table with hidden field that contains the 'billID'.
However when tested it gives an error For input String : "undefined". I think the error should be in billid hidden field somehow not been set? But I'm not sure and would like a bit of help.
.jsp HTML table.
<form id="formBill" name="formBill">
UserID : <input id="UserID" name="UserID" type="text" class= "form-control form-control-sm" required> <br>
Billing Date (yyyy-mm-dd): <input id="BillingDate" name="BillingDate" type="text" class= "form-control form-control-sm" required> <br>
Unit Cost : <input id="UnitCost" name="UnitCost" type="text" class="form-control form-control-sm" required> <br>
Units Used : <input id="UnitsUsed" name="UnitsUsed" type="text" class="form-control form-control-sm" required> <br>
Service Charge : <input id="ServiceCharge" name="ServiceCharge" type="text" class="form-control form-control-sm" required> <br>
Bill Settled : <select id="BillSettled" name="BillSettled" required>
<option value="false">False</option>
<option value="true">True</option>
</select>
<br><br><br>
<input id="btnSave" name="btnSave" type="button" value="Save" class="btn btn-primary">
<input type="hidden" id="hidBillIDSave" name="hidBillIDSave" value="">
</form>
<br>
<div id="alertSuccess" class="alert alert-success"></div>
<div id="alertError" class="alert alert-danger"></div>
<br>
<div id="divItemsGrid">
</div>
The dynamically generated table is placed in the divItemsGrid div.
Here are the Jquery ajax code
// Save =================================================
$(document).on("click", "#btnSave", function(event) {
// Clear alerts---------------------
$("#alertSuccess").text("");
$("#alertSuccess").hide();
$("#alertError").text("");
$("#alertError").hide();
// Form validation-------------------
var status = validateBillForm();
if (status != true) {
$("#alertError").text(status);
$("#alertError").show();
return;
}
//var type = ($("#hidItemIDSave").val() == "") ? "POST" : "PUT";
var type;
if ($("#hidBillIDSave").val() == ""){
type = "POST";
}
else{
type = "PUT";
}
$.ajax(
{
url: "BillsAPI",
type: type,
data: $("#formBill").serialize(),
dataType: "text",
error: function(response, status, error) {
console.log(response);
},
complete: function(response, status)
{
onBillSaveComplete(response.responseText, status);
}
});
});
// UPDATE==========================================
$(document).on("click", ".btnUpdate", function(event) {
$("#hidBillIDSave").val($(this).data("billID"));
$("#UserID").val($(this).closest("tr").find('td:eq(0)').text());
$("#BillingDate").val($(this).closest("tr").find('td:eq(1)').text());
$("#UnitCost").val($(this).closest("tr").find('td:eq(2)').text());
$("#UnitsUsed").val($(this).closest("tr").find('td:eq(3)').text());
$("#ServiceCharge").val($(this).closest("tr").find('td:eq(4)').text());
$("#BillSettled").val($(this).closest("tr").find('td:eq(5)').text());
});
// DELETE==============================================
$(document).on("click", ".btnRemove", function(event) {
$.ajax(
{
url: "BillsAPI",
type: "DELETE",
data: "billID=" + $(this).data("billID"),
dataType: "text",
complete: function(response, status) {
onBillDeleteComplete(response.responseText, status);
}
});
});
The update function sets the values into the form. If there is a hidden value then we use PUT to update the table. If not it becomes a POST.
I believe the error is here. Somehow the hidden billID value must not be getting set.
Below are the CRUD functions. They are a bit long but the dynamically generated table is in the read function.
//Create Bills
public String createBill(String BillingDate, String unitCost, String unitsUsed, String serviceCharge, String billSettled, String userID) {
String output = "";
try {
Connection con = connect();
if(con == null) {
return "Error while connecting to the database for inserting.";
}
//calculate total cost
int totalCost = (Integer.parseInt(unitCost) * Integer.parseInt(unitsUsed)) + Integer.parseInt(serviceCharge);
//create a prepared statement
String query = "insert into bills (`billDate`, `unitCost`, `unitsUsed`, `serviceCharge`, `totalCost`, `settled`, `userID`)"
+" values(?,?,?,?,?,?,?)";
PreparedStatement preparedStmt = con.prepareStatement(query);
//converting String to util.Date to sql.Date
java.util.Date date1 = new SimpleDateFormat("yyyy-MM-dd").parse(BillingDate);
java.sql.Date date2 = new java.sql.Date(date1.getTime());
// binding values
preparedStmt.setDate(1, date2);
preparedStmt.setInt(2, Integer.parseInt(unitCost));
preparedStmt.setInt(3, Integer.parseInt(unitsUsed));
preparedStmt.setInt(4, Integer.parseInt(serviceCharge));
preparedStmt.setInt(5, totalCost);
preparedStmt.setBoolean(6, Boolean.parseBoolean(billSettled));
preparedStmt.setInt(7, Integer.parseInt(userID));
// execute the statement
preparedStmt.execute();
con.close();
//output = "Inserted successfully";
String newBills = readBills();
output = "{\"status\":\"success\", \"data\": \"" + newBills + "\"}";
}
catch(Exception e) {
//output = "Error while inserting the item.";
output = "{\"status\":\"error\", \"data\": \"Error while inserting the item.\"}";
System.err.println(e.getMessage());
}
return output;
}
//Update Bills
//for settles bills
public String updateSettledBills(String billID, String billSettled) {
String output = "";
Connection con = connect();
try {
if(con == null) {
return "Error while connecting to the database for updating.";
}
//create prepared statement
String query = "update bills set settled=? where billID=?";
PreparedStatement preparedStmt = con.prepareStatement(query);
//binding values
preparedStmt.setBoolean(1, Boolean.parseBoolean(billSettled));
preparedStmt.setInt(2, Integer.parseInt(billID));
//execute statement
preparedStmt.execute();
con.close();
//output = "Updated successfully";
String newBills = readBills();
output = "{\"status\":\"success\", \"data\": \"" + newBills + "\"}";
}
catch(Exception e) {
//output = "Error while updating bill";
output = "{\"status\":\"error\", \"data\": \"Error while inserting the item.\"}";
System.err.println(e.getMessage());
}
return output;
}
//Delete Bills
public String deleteBill(String billID) {
String output = "";
try {
Connection con = connect();
if(con == null) {
return "Error while connecting to the database for deleting.";
}
//create prepared statement
String query = "delete from bills where billID=?";
PreparedStatement preparedStmt = con.prepareStatement(query);
// binding values to prepared statement
preparedStmt.setInt(1, Integer.parseInt(billID));
// execute the statement
preparedStmt.execute();
con.close();
//output = "Deleted successfully";
String newBills = readBills();
output = "{\"status\":\"success\", \"data\": \"" + newBills + "\"}";
}
catch(Exception e) {
//output = "Error while deleting the bill.";
output = "{\"status\":\"error\", \"data\": \"Error while inserting the item.\"}";
System.err.println(e.getMessage());
}
return output;
}
Finally, here are the servlets.
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String output = billObj.createBill(
request.getParameter("BillingDate"),
request.getParameter("UnitCost"),
request.getParameter("UnitsUsed"),
request.getParameter("ServiceCharge"),
request.getParameter("BillSettled"),
request.getParameter("UserID"));
response.getWriter().write(output);
}
// Convert request parameters to a Map
private static Map getParasMap(HttpServletRequest request) {
Map<String, String> map = new HashMap<String, String>();
try {
Scanner scanner = new Scanner(request.getInputStream(), "UTF-8");
String queryString = scanner.hasNext() ? scanner.useDelimiter("\\A").next() : "";
scanner.close();
String[] params = queryString.split("&");
for (String param : params) {
String[] p = param.split("=");
map.put(p[0], p[1]);
}
} catch (Exception e) {
}
return map;
}
/**
* #see HttpServlet#doPut(HttpServletRequest, HttpServletResponse)
*/
protected void doPut(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Map paras = getParasMap(request);
//System.out.println(paras.get("billID").toString());
String output = billObj.updateSettledBills(
paras.get("billID").toString(),
paras.get("BillSettled").toString());
response.getWriter().write(output);
}
/**
* #see HttpServlet#doDelete(HttpServletRequest, HttpServletResponse)
*/
protected void doDelete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Map paras = getParasMap(request);
String output = billObj.deleteBill(paras.get("billID").toString());
response.getWriter().write(output);
}
Sorry for the bloated post. I would greatly appreciate some with regards to this.
I create application similar to https://www.callicoder.com/spring-boot-file-upload-download-rest-api-example/
But I use Spring Security and this is the reason of error (if I remove Spring Security all work correctly):
{"timestamp":"2018-08-20T09:26:44.223+0000","status":403,"error":"Forbidden","message":"Forbidden","path":"/uploadFile"}
What I have to change for avoid this problem?
FileController:
#RestController
public class FileController {
private final FileStorageService fileStorageService;
#Autowired
public FileController(FileStorageService fileStorageService) {
this.fileStorageService = fileStorageService;
}
#PostMapping("/uploadFile")
public UploadFileResponse uploadFile(#RequestParam("file") MultipartFile file) {
String filename = fileStorageService.storeFile(file);
String fileDownloadUri = ServletUriComponentsBuilder.fromCurrentContextPath()
.path("/downloadFile/")
.path(filename)
.toUriString();
return new UploadFileResponse(
filename,
fileDownloadUri,
file.getContentType(),
file.getSize()
);
}
//...
}
upload-files.html with vanila js script that send post query:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0">
<title>Spring Boot File Upload / Download Rest API Example</title>
<link rel="stylesheet" href="/css/main.css" />
</head>
<body>
<div class="upload-container">
<div class="upload-header">
<h2>File Upload</h2>
</div>
<div class="upload-content">
<div class="single-upload">
<h3>Upload Single File</h3>
<form id="singleUploadForm" name="singleUploadForm">
<input id="singleFileUploadInput" type="file" name="file" class="file-input" required />
<button type="submit" class="primary submit-btn">Submit</button>
</form>
<div class="upload-response">
<div id="singleFileUploadError"></div>
<div id="singleFileUploadSuccess"></div>
</div>
</div>
</div>
</div>
</body>
<script>
'use strict';
var singleUploadForm = document.querySelector('#singleUploadForm');
var singleFileUploadInput = document.querySelector('#singleFileUploadInput');
var singleFileUploadError = document.querySelector('#singleFileUploadError');
var singleFileUploadSuccess = document.querySelector('#singleFileUploadSuccess');
function uploadSingleFile(file) {
var formData = new FormData();
formData.append("file", file);
var xhr = new XMLHttpRequest();
xhr.open("POST", "/uploadFile");
xhr.onload = function() {
console.log(xhr.responseText);
var response = JSON.parse(xhr.responseText);
if(xhr.status == 200) {
singleFileUploadError.style.display = "none";
singleFileUploadSuccess.innerHTML = "<p>File Uploaded Successfully.</p><p>DownloadUrl : <a href='" + response.fileDownloadUri + "' target='_blank'>" + response.fileDownloadUri + "</a></p>";
singleFileUploadSuccess.style.display = "block";
} else {
singleFileUploadSuccess.style.display = "none";
singleFileUploadError.innerHTML = (response && response.message) || "Some Error Occurred";
}
}
xhr.send(formData);
}
singleUploadForm.addEventListener('submit', function(event){
var files = singleFileUploadInput.files;
if(files.length === 0) {
singleFileUploadError.innerHTML = "Please select a file";
singleFileUploadError.style.display = "block";
}
uploadSingleFile(files[0]);
event.preventDefault();
}, true);
</script>
</html>
UPDATE
WebSecurityConfig:
#Configuration
#EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
private static final String USER_NOT_FOUND_PASSWORD = "userNotFoundPassword";
private final CustomUserDetailsService userDetailsService;
#Autowired
public WebSecurityConfig(CustomUserDetailsService userDetailsService) {
this.userDetailsService = userDetailsService;
}
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService)
.passwordEncoder(getPasswordEncoder());
}
private PasswordEncoder getPasswordEncoder() {
return new PasswordEncoder() {
#Override
public String encode(CharSequence charSequence) {
return charSequence.toString();
}
#Override
public boolean matches(CharSequence charSequence, String encoded) {
return !encoded.equals(USER_NOT_FOUND_PASSWORD)
&& BCrypt.checkpw(charSequence.toString(), encoded);
}
};
}
}
#Override
public void configure(WebSecurity web) throws Exception {
web.ignoring()
// Spring Security should completely ignore URLs starting with /resources/
.antMatchers("/resources/**");
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/public/**").permitAll().anyRequest()
.hasRole("USER").and()
// Possibly more configuration ...
.formLogin() // enable form based log in
// set permitAll for all URLs associated with Form Login
.permitAll();
}
You should add access persmission to url's otherwise spring security won't allow to access.
Hi I'm trying to open hosted angular app to my application without using iFrame , Object and embed tags. Below is my Handler code. Css and js files are loaded properly but site is not working as expected.
**web.config app settings:**
<add key="ProxyMode" value="1"/>
<add key="RemoteWebSite" value="http://localhost/angulartest"/>
**Handler :**
public class ReverseProxy : IHttpHandler
{
private static string GetContentType(string url)
{
if (url.ToLower().Contains(".css"))
{
return "text/css";
}
else if (url.ToLower().Contains(".js"))
{
return "application/javascript";
}
else
{
return "text/html";
}
}
/// <summary>
/// Method calls when client request the server
/// </summary>
/// <param name="context">HTTP context for client</param>
public void ProcessRequest(HttpContext context)
{
//read values from configuration file
int proxyMode = Convert.ToInt32(ConfigurationSettings.AppSettings["ProxyMode"]);
string remoteWebSite = ConfigurationSettings.AppSettings["RemoteWebSite"];
string remoteUrl;
if (proxyMode == 0)
remoteUrl = ParseURL(context.Request.Url.AbsoluteUri); //all site accepted
else
remoteUrl = context.Request.Url.AbsoluteUri.Replace("http://" + context.Request.Url.Host + context.Request.ApplicationPath, remoteWebSite); //only one site accepted
//create the web request to get the remote stream
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(remoteUrl);
//TODO : you can add your own credentials system
//request.Credentials = CredentialCache.DefaultCredentials;
HttpWebResponse response;
try
{
response = (HttpWebResponse)request.GetResponse();
}
catch (System.Net.WebException ex)
{
string dsdl;
using (var sr = new StreamReader(ex.Response.GetResponseStream()))
dsdl = sr.ReadToEnd();
//remote url not found, send 404 to client
context.Response.StatusCode = 404;
context.Response.StatusDescription = "Not Found";
context.Response.Write(dsdl);
context.Response.End();
return;
}
Stream receiveStream = response.GetResponseStream();
context.Response.ContentType = GetContentType(remoteUrl);
StreamReader readStream = new StreamReader(receiveStream, Encoding.Default);
Uri test = new Uri(remoteUrl);
string content;
if (proxyMode == 0)
content = ParseHtmlResponse(readStream.ReadToEnd(), context.Request.ApplicationPath + "/http//" + test.Host);
else
content = ParseHtmlResponse(readStream.ReadToEnd(), context.Request.ApplicationPath);
//write the updated HTML to the client
context.Response.Write(content);
//close streams
readStream.Close();
response.Close();
context.Response.End();
}
/// <summary>
/// Get the remote URL to call
/// </summary>
/// <param name="url">URL get by client</param>
/// <returns>Remote URL to return to the client</returns>
public string ParseURL(string url)
{
if (url.IndexOf("http/") >= 0)
{
string externalUrl = url.Substring(url.IndexOf("http/"));
return externalUrl.Replace("http/", "http://");
}
else
return url;
}
/// <summary>
/// Parse HTML response for update links and images sources
/// </summary>
/// <param name="html">HTML response</param>
/// <param name="appPath">Path of application for replacement</param>
/// <returns>HTML updated</returns>
public string ParseHtmlResponse(string html, string appPath)
{
html = html.Replace("\"/", "\"" + appPath + "/");
html = html.Replace("'/", "'" + appPath + "/");
html = html.Replace("=/", "=" + appPath + "/");
return html;
}
///
/// Specifies whether this instance is reusable by other Http requests
///
public bool IsReusable
{
get
{
return true;
}
}
}
Controller HTML is not firing. Attached Fiddler response also.
angulartest => Hosted angular application
ReverseProxy => My own application
Inbox.html not firing in my ReverseProxy project..
Please help me for this.
Finally I found the answer. Hosted application angular js relative path not taking during Reverse Proxy. So I added in CDN version of angular js in index.html,
Now it's working perfectly.
I'm try to upload image in database, i'm using drobzone.js
that's my controller code
[HttpGet]
public ActionResult Show(int? id)
{
string mime;
byte[] bytes = LoadImage(id.Value, out mime);
return File(bytes, mime);
}
[HttpPost]
public ActionResult Upload()
{
SuccessModel viewModel = new SuccessModel();
if (Request.Files.Count == 1)
{
var name = Request.Files[0].FileName;
var size = Request.Files[0].ContentLength;
var type = Request.Files[0].ContentType;
viewModel.Success = HandleUpload(Request.Files[0].InputStream, name, size, type);
}
return Json(viewModel);
}
private bool HandleUpload(Stream fileStream, string name, int size, string type)
{
bool handled = false;
try
{
byte[] documentBytes = new byte[fileStream.Length];
fileStream.Read(documentBytes, 0, documentBytes.Length);
Pictures databaseDocument = new Pictures
{
ProfilePicture=documentBytes,
FName=name,
Size=size,
Type=type
};
using(var contxt=new EnglisCenterEntities())
{
contxt.Pictures.Add(databaseDocument);
handled = (contxt.SaveChanges() > 0);
}
}
catch (Exception )
{
// Oops, something went wrong, handle the exception
}
return handled;
}
private byte[] LoadImage(int id, out string type)
{
byte[] fileBytes = null;
string fileType = null;
using(var contxt=new EnglisCenterEntities())
{
var databaseDocument = contxt.Pictures.FirstOrDefault(doc => doc.IdPicture == id);
if (databaseDocument != null)
{
fileBytes = databaseDocument.ProfilePicture;
fileType = databaseDocument.Type;
}
}
type = fileType;
return fileBytes;
}
and this is my script
<script type="text/javascript">
$(document).ready(function () {
$("#preview").fadeOut(15);
$("#refreshButton").click(function () {
var imageToLoad = $("#imageId").val();
if (imageToLoad.length > 0) {
$("#preview").attr("src", "/Document/Show/" + imageToLoad);
$("#preview").fadeIn();
}
});
});
and this is my view
<form action="/Document/Upload" class="dropzone" id="my-awesome-dropzone"></form>
<input type="text" name="imageId" id="imageId" />
<button type="button" id="refreshButton">Update Image</button>
<img src="/" style="display: none" id="preview" />
and it's working with multi images but i want to save single image and prevent the user put more than one image. Is there a way to save a single image and to prevent user put more than an image using dropzone.js?
Javascript is needed to limit maxFiles, see http://www.dropzonejs.com/#configuration-options and http://jsfiddle.net/P2dTF/2/ for example:
Dropzone.autoDiscover = true;
Dropzone.options.my-awesome-dropzone = {
maxFiles: 1
};
[HttpPost]
public ActionResult Upload(HttpPostedFileBase file)
{
SuccessModel viewModel = new SuccessModel();
if (file != null)
{
viewModel.Success = HandleUpload(file);
}
return Json(viewModel);
}
Param name of file is important, dropzone binds single upload to param file (and multiple to a param array of files). Don't see why you need a fileStream though, fileStream is needed when you want to return a range of bytes for example with a Request Header (audio) for partial download, HttpPostedFileBase does the job in your case.
private bool HandleUpload(HttpPostedFileBase file)
{
bool handled = false;
try
{
byte[] documentBytes = new byte[file.ContentLength];
Pictures databaseDocument = new Pictures
{
ProfilePicture=documentBytes,
FName=file.FileName,
Size=file.ContentLength,
Type=file.ContentType
};
using(var contxt=new EnglisCenterEntities())
{
contxt.Pictures.Add(databaseDocument);
handled = (contxt.SaveChanges() > 0);
}
}
catch (Exception )
{
// Oops, something went wrong, handle the exception
}
return handled;
}
// Step 1
function doSubmit(data1, data2){
$("#dataForm").remove();
var form = '';
form += '<form name="dataForm" id="dataForm" action="" target="hiddenIframe" method="post" enctype="multipart/form-data" accept-charset="UTF-8">';
form += '<input type="text" name="data1" id="data1"/>';
form += '<input type="text" name="data2" id="data2"/>';
form += '<div name="dataFormTarget" id="dataFormTarget" style="display:none">';
form += '</div>';
form += '</form>';
$('body').append(form);
$("#dataForm data1").val(data1);
$("#dataForm data2").val(data2);
$("#dataForm").attr("action", "/download/fileDownload.do");
$("#dataForm").submit(function(event){
event.preventDefault();
$.ajax({
url : "/download/fileDownload.do",
async : true,
type : "POST",
data : {
"data1" : data1,
"data2" : data2
},
contentType : "application/x-www-form-urlencoded; charset=UTF-8",
processData : true,
success : function(data){
var blob=new Blob([data]);
var link=document.createElement('a');
link.href=window.URL.createObjectURL(blob);
link.download="testFile.zip";
link.click();
}
});
});
$("#dataForm").submit();
}
// Step 2
#RequestMapping(value = "/download/fileDownload.do")
public ModelAndView fileDownload(HttpServletRequest request, HttpServletResponse response, ModelAndView mav) throws Exception {
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
Parameter inMap = rDictionary(request, response);
Parameter outMap = new Parameter();
Parameter errorMap = new Parameter();
File file = null;
try {
file = new File(inMap.get("data1"));
errorMap = Util.putErrorMap(ErrConst.ERROR_SUCCESS_CODE, null, inMap);
} catch (Exception e) {
e.printStackTrace();
}
mav.addObject("outMap", outMap);
mav = new ModelAndView("downloadView", "downloadFile", file);
return mav;
}
// Step 3
public class DownloadView extends AbstractView {
private static final Logger logger = LogManager.getLogger(DownloadView.class);
public DownloadView() {
setContentType("application/download; charset=utf-8");
}
#Override
protected void renderMergedOutputModel(Map<String, Object> model,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
File file = null;
try{
file = (File) model.get("downloadFile");
response.setContentType(getContentType());
response.setContentLength((int) file.length());
String fileName = URLEncoder.encode(file.getName(), "UTF-8");
response.setHeader("Content-Disposition", "attachment; filename=\""
+ fileName + "\";");
response.setHeader("Content-Transfer-Encoding", "binary");
OutputStream out = response.getOutputStream();
FileInputStream fis = null;
try {
fis = new FileInputStream(file);
FileCopyUtils.copy(fis, out);
} finally {
if (fis != null) {
try {
fis.close();
} catch (IOException ioe) {
}
}
}
out.flush();
}catch(Exception e){
logger.error("file not found Excpetion !!!["+ file.getPath() +"]");
}
}
}
Hi.
I'm trying to zip file download, using above code.
after download complete, I must need callback function for next download.
When run this code, download is occured.
but downloaded zip file was crashed..
I don't know what is wrong.
Please give me solution.
Thanks.
(Sorry for short english.)