Compartilhe um upload de arquivo e faça o download e compacte a imagem usada no projeto e extraído diretamente do projeto :)
A cópia do código é a seguinte:
pacote com.eabax.plugin.yundada.utils;
importar java.awt.image.bufferiMage;
importar java.io.file;
importar java.io.ioException;
importar java.text.simpledateFormat;
importar java.util.date;
importar java.util.list;
importar java.util.uuid;
importar javax.imageio.imageio;
importar javax.servlet.http.httpServletRequest;
importação net.coobird.thumbnailator.thumbnails;
importar org.apache.commons.fileupload.fileitem;
importar org.apache.commons.fileupload.disk.diskfileItemFactory;
importar org.apache.commons.fileupload.servlet.servletfileUpload;
importar org.json.jsonObject;
importar org.slf4j.logger;
importar org.slf4j.loggerFactory;
importar com.eabax.plugin.yundada.gacontext;
classe pública FileUploadDownloadUtil {
Log do Logger final estático privado = LoggerFactory.getLogger (FileUploadDownloadUtil.class);
/**
* Carregar arquivos para o servidor
* @param solicitação
* Tipo @param
* @retornar
* @Throws Exception
*/
upload public static string (solicitação httpServletRequest, tipo string) lança a exceção {
boolean ismultipart = servletfileUpload.ismultipartContent (solicitação);
String savefilename = null;
if (ismultipart) {
String savePath = request.getSession (). GetServletContext ()
.GetRealPath ("/")
+ "/upload/";
String temppath = request.getSession (). GetServletContext ()
.GetRealPath ("/")
+ "/upload/temp/";
Arquivo savefile = novo arquivo (savePath);
Arquivo tempfile = novo arquivo (temppath);
if (! savefile.isdirectory ())
savefile.mkdirs ();
if (! tempfile.isdirectory ())
tempfile.mkdirs ();
DiskFileItemFactory Factory = new DiskFileItemFactory ();
Factory.SetSizETHreshold (1024 * 4);
Factory.SetRepository (TempFile);
ServindFileUpload uploader = new ServletFileUpload (fábrica);
uploader.SetSizEMAX (20 * 1024 * 1024);
List <FileItem> fileItems = uploader.parserequest (request);
para (Item FileItem: FileItems) {
if (item.isformfield ()) {
// funname = item.getString ();
} outro {
// string filename = item.getName ();
// Corda
// FIX = FILENAME.SUBSTRING (FILENAME.LASTIndexOf (".")+1);
String fix = type;
Data agoradate = new Date ();
SimpledateFormat sdf = new SimpleDateFormat (
"yyyymmddhhmmss");
String filename = sdf.format (NowDate);
nome do arquivo += system.currenttimemillis ();
nome do arquivo + = "."
saveFilename = "/upload/" + nome do arquivo;
Arquivo de arquivo = novo arquivo (savepath + filename);
item.write (arquivo);
}
}
}
retornar savefilename;
}
/**
* Carregue o avatar
* @param solicitação
* Tipo @param
* @retornar
* @Throws Exception
*/
public static string uploadheadheadshow (solicitação httpServletRequest, contexto de gacontext, tipo de string) lança a exceção {
boolean ismultipart = servletfileUpload.ismultipartContent (solicitação);
String savefilename = null;
String imagepath = "/upload/headshow/";
String x = request.getParameter ("comprimento");
String y = request.getParameter ("wide");
if (ismultipart) {
String headshowsServicePath = request.getSession (). GetServletContext ()
.GetRealPath ("/")
+ ImagePath;
Data agoradate = new Date ();
SimpledateFormat sdf = new SimpleDateFormat (
"yyyymmddhhmmss");
String filename = context.getUserName ()+sdf.format (NowDate);
Arquivo headshowfile = novo arquivo (headshowServicePath);
if (! headshowfile.isdirectory ())
headshowfile.mkdirs ();
DiskFileItemFactory Factory = new DiskFileItemFactory ();
Factory.SetSizETHreshold (1024 * 4);
Factory.SetRepository (Headshowfile);
ServindFileUpload uploader = new ServletFileUpload (fábrica);
uploader.SetSizEMAX (20 * 1024 * 1024);
List <FileItem> fileItems = uploader.parserequest (request);
para (Item FileItem: FileItems) {
if (item.isformfield ()) {
// funname = item.getString ();
} outro {
String fix = type;
nome do arquivo + = "."
saveFileName = ImagePath + FileName;
Arquivo de arquivo = novo arquivo (headshowServicePath + FileName);
item.write (arquivo);
}
}
// compacte a imagem
if (x!
saveFilename = ThumbnailatorImage (ImagePath, FileName, Type, Integer.parseint (x), Integer.parseint (y));
}
}
retornar savefilename;
}
/**
* Carregar e compartilhar fotos
* @param solicitação
* Tipo @param
* @retornar
* @Throws Exception
*/
public static jsonObject uploadarticleImage (solicitação httpServletRequest, contexto de gacontext, tipo de string) lança exceção {
boolean ismultipart = servletfileUpload.ismultipartContent (solicitação);
JsonObject saveFileName = new jsonObject ();
String imagePath = "";
String x = request.getParameter ("comprimento");
String y = request.getParameter ("wide");
if ("4" .equals (tipo)) {
// Compartilhe o caminho da imagem de upload
ImagePath = "/Upload/ArticleImage/";
} else if ("5" .equals (tipo)) {
// Link de upload Path Image
ImagePath = "/upload/linkImage/";
} outro {
// O caminho para fazer upload de avatar
ImagePath = "/Upload/Headshow/";
}
if (ismultipart) {
String headshowsServicePath = request.getSession (). GetServletContext ()
.GetRealPath ("/")
+ ImagePath;
Arquivo headshowfile = novo arquivo (headshowServicePath);
if (! headshowfile.isdirectory ())
headshowfile.mkdirs ();
DiskFileItemFactory Factory = new DiskFileItemFactory ();
Factory.SetSizETHreshold (1024 * 4);
Factory.SetRepository (Headshowfile);
ServindFileUpload uploader = new ServletFileUpload (fábrica);
uploader.SetSizEMAX (20 * 1024 * 1024);
List <FileItem> fileItems = uploader.parserequest (request);
para (Item FileItem: FileItems) {
Uuid uuid = uuid.randomuuid ();
String filename = uuid.toString ();
if (item.isformfield ()) {
// funname = item.getString ();
} outro {
String fix = type;
nome do arquivo + = "."
saveFilename.put (uuid.toString (), imagepath + filename);
Arquivo de arquivo = novo arquivo (headshowServicePath + FileName);
item.write (arquivo);
}
// compacte a imagem
if (x!
String thumbnailArorName = thumbnailatorImage (imagepath, nome do arquivo, tipo, número inteiro.parseint (x), número inteiro.parseint (y));
saveFilename.put ("ThumbnailatorImage", thumbnailatorname);
}
}
}
retornar savefilename;
}
/**
* Carregar compactação e salvar fotos
* @param OldSavePath Original File Path
* @param OldFileName Nome do arquivo original
* @param corrigir tipo de arquivo
* @param x largura necessária para compactação
* @param y O comprimento necessário para a compactação
* @retornar
* @THOWSows IoException
*/
public static string thumbnailatorImage (string OldSavePath, String OldFilename, String Fix, int x, int y) lança ioexception {
// Miniatura Leia e comprime fotos
BufferImage WatermarkBufferImage = miniaturas.of (OldSavePath+OldFileName)
// Método de miniatura, compactar fotos
.Size (x, y)
// leia como um objeto bufferimage
.AsBufferedImage ();
// Escreva as figuras na memória no arquivo especificado
String savePath = OldSavePath+x+"-"+y+"/";
Arquivo savefile = novo arquivo (savePath);
if (! savefile.isdirectory ())
savefile.mkdirs ();
DiskFileItemFactory Factory = new DiskFileItemFactory ();
Factory.SetSizETHreshold (1024 * 4);
Factory.SetRepository (SaveFile);
ServindFileUpload uploader = new ServletFileUpload (fábrica);
uploader.SetSizEMAX (20 * 1024 * 1024);
Uuid uuid = uuid.randomuuid ();
String filename = uuid.toString ();
nome do arquivo + = "."
String savefilename = salvePath+filename;
Arquivo fileOutput = novo arquivo (saveFilename);
Imageio.write (WaterMarkBufferImage, FIX, FileOutput);
retornar savefilename;
}
/**
* Download de comprimido e salve fotos
* @param OldSavePath Original File Path
* @param OldFileName Nome do arquivo original
* @param corrigir tipo de arquivo
* @param x largura necessária para compactação
* @param y O comprimento necessário para a compactação
* @retornar
* @THOWSows IoException
*/
public static string downloadthumbnailatorImage (string servicePath, string uri, int x, int y) lança ioexception {
// Verifique se a imagem existe
String urisubpath = uri.substring (0, uri.lastindexof ("/")+1); // antes do nome do arquivo, após o servidor
String filename = uri.substring (uri.lastindexof ("/")+1, uri.length ()); // nome do arquivo
String getThumbnailatorPath = ServicePath+UrisubPath+X+"-"+y+"/";
String savefilename = getThumbnailatorPath+filename;
Arquivo downfilepath = novo arquivo (getthumbnailatorpath); // compactar a pasta após a compactação
Arquivo downfile = novo arquivo (savefilename); // compacte o arquivo após ele
if (downfilepath.isdirectory () && downfile.exists ()) {
retornar savefilename;
} outro {
// Miniatura Leia e comprime fotos
log.error (serviço de serviço+uri);
BufferImage WaterMarkBufferImage = miniaturas.of (ServicePath+URI)
// Método de miniatura, compactar fotos
.Size (x, y)
// leia como um objeto bufferimage
.AsBufferedImage ();
if (! DownFilePath.isDirectory ()) {
DownFilePath.mkdirs ();
}
DiskFileItemFactory Factory = new DiskFileItemFactory ();
Factory.SetSizETHreshold (1024 * 4);
Factory.SetRepository (DownFilePath);
ServindFileUpload uploader = new ServletFileUpload (fábrica);
uploader.SetSizEMAX (20 * 1024 * 1024);
Arquivo fileOutput = novo arquivo (saveFilename);
Imageio.Write (WaterMarkBufferImage, "JPG", FileOutput);
}
retornar savefilename;
}
}
O exposto acima é todo o conteúdo compartilhado neste artigo, espero que seja útil para todos.