Comparta una carga de archivo y descarga y comprimir la imagen utilizada en el proyecto, y extraída directamente del proyecto :)
La copia del código es la siguiente:
paquete com.eabax.plugin.yundada.utils;
import java.awt.image.bufferedImage;
import java.io.file;
import java.io.ioException;
import java.text.simpledateFormat;
import java.util.date;
import java.util.list;
import java.util.uuid;
import javax.imageio.imageio;
import javax.servlet.http.httpservletRequest;
importar 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;
import com.eabax.plugin.yundada.gacontext;
clase pública FileUploaddownloadUtil {
Private static final logger log = loggerFactory.getLogger (fileUploadDownloadUtil.class);
/**
* Cargar archivos al servidor
* @Param Solicitud
* @param tipo
* @devolver
* @@throws Exception
*/
Public static string upload (httpservletRequest, tipo de cadena) lanza la excepción {
boolean isMultipart = servletFileUpload.IsmultipartContent (solicitud);
String saveFileName = null;
if (isMultipart) {
String SavePath = request.getSession (). GetServletContext ()
.getRealPath ("/")
+ "/upload/";
Cadena temppath = request.getSession (). GetServletContext ()
.getRealPath ("/")
+ "/upload/temp/";
Archivo saveFile = nuevo archivo (savePath);
Archivo tempfile = nuevo archivo (TEMPPATH);
if (! saveFile.isDirectory ())
saveFile.mkDirs ();
if (! tempfile.isDirectory ())
tempfile.mkdirs ();
DiskFileItemFactory fábrica = new DiskFileItemFactory ();
Factory.setsizethreshold (1024 * 4);
factory.setRepository (tempfile);
ServletFileUpload uploader = new ServLetFileUpload (fábrica);
por carga.setsizeMax (20 * 1024 * 1024);
List <FilleItem> fileItems = uploader.parserequest (solicitud);
para (el elemento fileitem: fileItems) {
if (item.isformfield ()) {
// funname = item.getString ();
} demás {
// cadena filename = item.getName ();
// Cadena
// fix = filename.substring (filename.lastIndexof (".")+1);
String Fix = type;
Date NowDate = new Date ();
SimpleDateFormat sdf = new SimpleDateFormat (
"yyyymmddhhmmmss");
Cadena filename = sdf.format (ahora date);
FileName += System.CurrentTimemillis ();
nombre de archivo + = "."
saveFileName = "/upload/" + FileName;
Archivo archivo = nuevo archivo (SavePath + FileName);
item.write (archivo);
}
}
}
return saveFileName;
}
/**
* Subir avatar
* @Param Solicitud
* @param tipo
* @devolver
* @@throws Exception
*/
Public static string uploadheadheadshow (solicitud httpservletrequest, contexto de gacontext, tipo de cadena) lanza la excepción {
boolean isMultipart = servletFileUpload.IsmultipartContent (solicitud);
String saveFileName = null;
String imagePath = "/upload/sheadshow/";
Cadena x = request.getParameter ("longitud");
Cadena y = request.getParameter ("amplio");
if (isMultipart) {
String HeadshowservicePath = request.getSession (). GetServletContext ()
.getRealPath ("/")
+ ImagePath;
Date NowDate = new Date ();
SimpleDateFormat sdf = new SimpleDateFormat (
"yyyymmddhhmmmss");
String filename = context.getUsername ()+sdf.format (nowdate);
Archivo WEADSHOWFILE = nuevo archivo (WotheSwowServicePath);
if (! sheadshowfile.isDirectory ())
showshowfile.mkdirs ();
DiskFileItemFactory fábrica = new DiskFileItemFactory ();
Factory.setsizethreshold (1024 * 4);
Factory.setRepository (WarteShowFile);
ServletFileUpload uploader = new ServLetFileUpload (fábrica);
por carga.setsizeMax (20 * 1024 * 1024);
List <FilleItem> fileItems = uploader.parserequest (solicitud);
para (el elemento fileitem: fileItems) {
if (item.isformfield ()) {
// funname = item.getString ();
} demás {
String Fix = type;
nombre de archivo + = "."
saveFileName = ImagePath + FileName;
Archivo archivo = nuevo archivo (starsShowservicePath + nombre de archivo);
item.write (archivo);
}
}
// comprimir la imagen
if (x! = null &&! "",. Equals (x) && y! = null &&! "",. Equals (y)) {
saveFileName = ThumbnailatorImage (ImagePath, nombre de archivo, tipo, integer.parseInt (x), integer.parseInt (y));
}
}
return saveFileName;
}
/**
* Subir y compartir fotos
* @Param Solicitud
* @param tipo
* @devolver
* @@throws Exception
*/
Public static jsonObject uploadArticleEmage (solicitud httpservletrequest, contexto gacontext, tipo de cadena) lanza la excepción {
boolean isMultipart = servletFileUpload.IsmultipartContent (solicitud);
JsonObject saveFileName = new JsonObject ();
Cadena imagePath = "";
Cadena x = request.getParameter ("longitud");
Cadena y = request.getParameter ("amplio");
if ("4" .equals (type)) {
// Comparte la ruta de imagen de carga
ImagePath = "/upload/artículoMage/";
} else if ("5" .equals (type)) {
// Enlace la ruta de imagen de carga
imagePath = "/upload/linkimage/";
} demás {
// El camino para cargar avatar
ImagePath = "/upload/sheadshow/";
}
if (isMultipart) {
String HeadshowservicePath = request.getSession (). GetServletContext ()
.getRealPath ("/")
+ ImagePath;
Archivo WEADSHOWFILE = nuevo archivo (WotheSwowServicePath);
if (! sheadshowfile.isDirectory ())
showshowfile.mkdirs ();
DiskFileItemFactory fábrica = new DiskFileItemFactory ();
Factory.setsizethreshold (1024 * 4);
Factory.setRepository (WarteShowFile);
ServletFileUpload uploader = new ServLetFileUpload (fábrica);
por carga.setsizeMax (20 * 1024 * 1024);
List <FilleItem> fileItems = uploader.parserequest (solicitud);
para (el elemento fileitem: fileItems) {
Uuid uuid = uuid.randomuuid ();
Cadena filename = uuid.ToString ();
if (item.isformfield ()) {
// funname = item.getString ();
} demás {
String Fix = type;
nombre de archivo + = "."
saveFileName.put (uuid.ToString (), imagePath + nombre de archivo);
Archivo archivo = nuevo archivo (starsShowservicePath + nombre de archivo);
item.write (archivo);
}
// comprimir la imagen
if (x! = null &&! "",. Equals (x) && y! = null &&! "",. Equals (y)) {
String ThumbnailAtorname = ThumbnailatorImage (ImagePath, nombre de archivo, tipo, Integer.ParseInt (x), Integer.ParseInt (y));
saveFileName.put ("ThumbnailatorInimage", Thumbnailatorname);
}
}
}
return saveFileName;
}
/**
* Cargar compresión y guardar imágenes
* @param OldSavePath Ruta de archivo original
* @param Nombre del archivo original de OldFilename
* @param corrige el tipo de archivo
* @param x Ancho requerido para la compresión
* @param y la longitud requerida para la compresión
* @devolver
* @throws ioexception
*/
public static String ThumbnailatorInimage (String OldSavePath, String OldFileName, String Fix, Int X, Int Y) lanza ioexception {
// Miniatura lee y comprime imágenes
BufferedImage WaterMarkBufferedImage = miniaturas.of (OldSavePath+OldFilename)
// método de miniatura, imágenes de compresa
.size (x, y)
// Leer como un objeto BufferedImage
.asbufferedImage ();
// Escribe las imágenes en la memoria al archivo especificado
String SavePath = OldSavePath+x+"-"+y+"/";
Archivo saveFile = nuevo archivo (savePath);
if (! saveFile.isDirectory ())
saveFile.mkDirs ();
DiskFileItemFactory fábrica = new DiskFileItemFactory ();
Factory.setsizethreshold (1024 * 4);
factory.setRepository (SaveFile);
ServletFileUpload uploader = new ServLetFileUpload (fábrica);
por carga.setsizeMax (20 * 1024 * 1024);
Uuid uuid = uuid.randomuuid ();
Cadena filename = uuid.ToString ();
nombre de archivo + = "."
String SaveFileName = SavePath+FileName;
Archivo fileOutput = nuevo archivo (saveverFileName);
ImageIO.Write (WaterMarkBufferedImage, Fix, FileOutput);
return saveFileName;
}
/**
* Descargue las imágenes comprimidas y guardadas
* @param OldSavePath Ruta de archivo original
* @param Nombre del archivo original de OldFilename
* @param corrige el tipo de archivo
* @param x Ancho requerido para la compresión
* @param y la longitud requerida para la compresión
* @devolver
* @throws ioexception
*/
public static string downloadthumbnailatorImage (String ServicePath, String Uri, int x, int y) lanza ioexception {
// Compruebe si la imagen existe
Cadena urisubpath = uri.substring (0, uri.lastindexof ("/")+1); // Antes del nombre del archivo, después del servidor
Cadena filename = uri.substring (uri.lastindexof ("/")+1, uri.length ()); // nombre de archivo
String getThumbnailatorPath = ServicePath+Urisubpath+x+"-"+y+"/";
String saveFileName = getThumbnailatorPath+FileName;
Archivo downfilePath = nuevo archivo (getThumbnailatorPath); // comprimir la carpeta después de que esté comprimido
Archivo downfile = nuevo archivo (saveFileName); // comprimir el archivo después de él
if (downfilePath.isDirectory () && downfile.exists ()) {
return saveFileName;
} demás {
// Miniatura lee y comprime imágenes
log.error (ServicePath+URI);
BufferedImage WaterMarkBufferedImage = miniaturas.of (ServicePath+URI)
// método de miniatura, imágenes de compresa
.size (x, y)
// Leer como un objeto BufferedImage
.asbufferedImage ();
if (! downfilePath.isDirectory ()) {
downfilepath.mkdirs ();
}
DiskFileItemFactory fábrica = new DiskFileItemFactory ();
Factory.setsizethreshold (1024 * 4);
Factory.setRepository (Downfilepath);
ServletFileUpload uploader = new ServLetFileUpload (fábrica);
por carga.setsizeMax (20 * 1024 * 1024);
Archivo fileOutput = nuevo archivo (saveverFileName);
ImageIO.Write (WaterMarkBufferedImage, "JPG", FileOutput);
}
return saveFileName;
}
}
Lo anterior es todo el contenido compartido en este artículo, espero que sea útil para todos.